🚀 Day 62: Foundations of Sorting — Bubble vs. Selection Logic 🔢 I’m 62 days into my Java journey, and today was all about order. I stepped into the world of Sorting Algorithms, exploring the mechanics of how we organize "jumbled" data into a structured sequence. 1. Bubble Sort (The "Rising" Logic) 🫧 ▫️ The Logic: It works by repeatedly stepping through the list, comparing adjacent elements and swapping them if they are in the wrong order. Why it's called Bubble? Because the largest elements "bubble up" to the end of the array with each pass. ▫️ Efficiency: While simple to implement, its (O(n^2)) time complexity makes it best for small datasets or nearly sorted lists. 2. Selection Sort (The "Minimum" Search) 🎯 ▫️ The Logic: This algorithm divides the array into a sorted and an unsorted part. It repeatedly finds the minimum element from the unsorted section and swaps it with the first element of that section. ▫️ The Advantage: Unlike Bubble Sort, it performs a maximum of (n-1) swaps, making it more efficient in terms of memory writes. ▫️ Efficiency: It also has an (O(n^2)) time complexity, but its logic is the basis for more advanced algorithms. 💡 My Key Takeaway: Sorting isn't just about the final result; it’s about understanding Swapping Logic and Nested Loop Control. These basic algorithms are the building blocks for the more complex ones I’ll be tackling next, like Quick Sort and Merge Sort. Question for the Developers: We know (O(n^2)) algorithms aren't the fastest for huge data, but which one do you find easier to explain to a beginner—Bubble or Selection? I’m finding the "Bubbling" visual very intuitive! 👇 #Java #CoreJava #SortingAlgorithms #BubbleSort #SelectionSort #100DaysOfCode #BackendDevelopment #DataStructures #LearningInPublic #CleanCode 10000 Coders Meghana M
Bubble vs Selection Sorting Algorithms in Java
More Relevant Posts
-
🚀 Beats 100% | Solved LeetCode 34: Find First and Last Position of Element in Sorted Array 🚀 Stoked to share a small win from today's coding session! Managed to achieve a 0 ms runtime, beating 100% of Java submissions on LeetCode! 🏁 💡 The Challenge Given a sorted array of integers, find the starting and ending position of a given target value in $O(\log n)$ time complexity. If the target isn't found, return [-1, -1]. 🧠 My Approach: Optimized Binary Search A simple linear scan would take $O(n)$ time, which isn't optimal for large datasets. Since the array is already sorted, Binary Search is the perfect tool—but with a twist. Instead of stopping as soon as the target is found, I split the logic into two independent helper methods: 1️⃣ Find First Occurrence: When nums[mid] == target, save the index and keep searching the left half (right = mid - 1) to find the absolute earliest boundary. 2️⃣ Find Last Occurrence: Conversely, when the target is found here, keep searching the right half (left = mid + 1) to lock down the final boundary. 📊 Complexity Time Complexity: $O(\log n)$ — Two independent binary search passes. Space Complexity: $O(1)$ — Fully in-place processing with zero auxiliary memory. Consistency pays off. Every problem solved is a step closer to mastering Data Structures and Algorithms! 💻🔥 #LeetCode #Java #DataStructures #Algorithms #BinarySearch #CodingLife #SoftwareEngineering #ProblemSolving #TechCommunity
To view or add a comment, sign in
-
-
Binary search on a sorted array is easy. Binary search on a rotated sorted array is where it gets interesting. Day 36 of #100DaysOfCode Today I solved LeetCode 33 - Search in Rotated Sorted Array, and this is one of those problems that every developer preparing for interviews must know. The problem: A sorted array has been rotated at some unknown pivot. Given a target, find its index in O(log n) time or return -1. How I approached it: The key observation is that even after rotation, at least one half of the array is always perfectly sorted. I used this fact to decide which half to search. At every step I calculated mid and checked two things. First, if nums[low] <= nums[mid], the left half is sorted. In that case if target lies within nums[low] and nums[mid], I searched left, otherwise I moved to the right half. If the left half is not sorted, the right half must be sorted. Then if target lies within nums[mid] and nums[high], I searched right, otherwise I moved to the left half. This gives a clean O(log n) solution with no extra space. What I learned from this problem: The real insight here is not binary search itself, it is knowing which half is still sorted at every step. Once you identify the sorted half, the rest of the logic is exactly like standard binary search. This problem teaches you to extract useful information from partial structure in data, which is a skill that goes far beyond just this one problem. 0ms runtime beating 100% was a great result today. #100DaysOfCode #LeetCode #DSA #Java #BinarySearch #Programming #SoftwareEngineering #CodingChallenge #InterviewPrep
To view or add a comment, sign in
-
-
📅 Date: May 3, 2026 Day 9 of my LeetCode Journey 🚀 ✅ Problem Solved: 22. Generate Parentheses 🧠 Approach & Smart Solution: This is a fantastic problem to master Backtracking and Depth-First Search (DFS)! Instead of generating all possible combinations of brackets and then validating them (which is highly inefficient), I built a recursive DFS function that only generates valid combinations on the fly. By keeping track of the counts of open and closed parentheses, we can smartly constrain the decision tree. • Pseudo-code: Initialize an empty result list and call a recursive DFS helper function. In the DFS function, track the current string, the count of 'open' brackets, and the count of 'close' brackets. Base Case: If the length of the built string reaches exactly 2 * n, we have formed a complete and valid sequence. Add it to the result list and return. Recursive Step 1: If the count of 'open' brackets is less than 'n', we are allowed to add an '(' and recursively call the function. Recursive Step 2: If the count of 'close' brackets is strictly less than the count of 'open' brackets, we are allowed to add a ')' and recursively call the function. This smart pruning ensures we never build an invalid parenthesis string, saving massive amounts of computational power! ⏱️ Time Complexity: O(4^n / √n) (Bounded by the n-th Catalan number, as we only generate valid combinations) 📦 Space Complexity: O(n) (Due to the maximum depth of the recursion call stack being 2n) 📊 Progress Update: • Streak: 9 Days 🔥 • Difficulty: Medium • Pattern: Backtracking / Depth-First Search (DFS) / String Manipulation 🔗 LeetCode Profile: https://lnkd.in/gBcDQwtb (@Hari312004) Understanding how to constrain decision trees early is the secret to mastering complex backtracking algorithms! 💡 #LeetCode #DSA #Backtracking #DFS #Java #CodingJourney #ProblemSolving #InterviewPrep #Consistency #BackendDevelopment
To view or add a comment, sign in
-
-
📌 Strengthening Binary Tree Concepts through Problem Solving Recently, I worked on LeetCode 297 – Binary Tree Serialization and Deserialization At first glance, it feels like a tree traversal problem… but the real learning? 👉 Understanding how to reconstruct data structures efficiently after converting them into a storable/transmittable format 🔍 Problem Design an algorithm to: 👉 Serialize a binary tree into a string 👉 Deserialize the string back into the original tree The challenge is simple to understand but interesting to implement: ✔️ Tree structure must remain unchanged after reconstruction ✔️ Null nodes matter ✔️ Parent-child relationships must be preserved 🧠 Approach Used: Level Order Traversal (BFS) Instead of recursion-based traversal, I used: 👉 Queue + Breadth First Search (Level Order Traversal) ⚙️ Serialization Logic: • Traverse the tree level by level • Store node values in a string • Store "null" for missing children Example: Tree: 1 / \ 2 3 / \ 4 5 Serialized Form: 1 2 3 null null 4 5 null null null null 📌 Why "null" is important? Without null values: ❌ Tree structure gets lost Different trees may produce the same sequence. Including nulls ensures: ✔️ Exact reconstruction of original structure 🧩 Deserialization Logic To rebuild the tree: • Read serialized values one by one • Use a queue to process parent nodes • Assign left and right children level by level • Skip "null" nodes 📌 Key Insight: Serialization stores traversal order + structure information. Deserialization reconstructs the tree by replaying that same order. ⏱️ Complexity Serialization: 👉 Time: O(n) 👉 Space: O(n) Deserialization: 👉 Time: O(n) 👉 Space: O(n) (where n = number of nodes) #DSA #LeetCode #BinaryTree #TreeTraversal #Serialization #Deserialization #Java #CodingInterview #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
🚀 Day 61: The Great Search — Linear vs. Binary Logic 🔍 Today’s Java session was a deep dive into how we find data. While searching for a value might seem simple, the difference between a "good" and an "optimal" approach can be the difference between a fast app and a lagging one! 1. Linear Search (Sequential Search) 🚶♂️ ▫️ The Logic: It’s the "brute force" method. You start at the beginning and check every element one by one until you find a match. ▫️ The Advantage: It’s extremely versatile—it works on both sorted and unsorted data. ▫️ The Catch: It’s slow for large datasets because its time complexity is (O(n)). 2. Binary Search (The Divide & Conquer Hero) ⚡ ▫️ The Logic: Instead of checking everything, it repeatedly halves the search space. It checks the middle element and immediately ignores the half where the target cannot exist. ▫️ The Advantage: It is incredibly fast, with a time complexity of (O(log n)). Searching through 1,000,000 items takes only about 20 comparisons! The Catch: It only works on sorted data. If your array isn't sorted, you have to sort it first. 💡 My Key Takeaway: As a developer, you don't always need the "fastest" algorithm; you need the right one for the job. Use Linear Search for small or messy lists, but reach for Binary Search whenever performance and scalability matter. To the Java Pros: When you have an unsorted list, do you usually Linear Search through it, or is it better to Sort + Binary Search? I’m curious to hear how you decide! 👇 #Java #CoreJava #SearchingAlgorithms #BinarySearch #LinearSearch #100DaysOfCode #BackendDevelopment #CleanCode #LearningInPublic 10000 Coders Meghana M
To view or add a comment, sign in
-
Today’s LeetCode Daily Problem 💻 LeetCode 3093. Longest Common Suffix Queries => Problem Task The problem asks us to find the string from wordsContainer having the longest common suffix with each query string. A brute force approach would compare every query with every container word and calculate suffix matches manually. • N = max wordsContainer.length = 10^4 • M = max wordsQuery.length = 10^4 • L = max string length = 5 * 10^3 Brute force time complexity becomes: O(N * M * L) > 10^8 which is far beyond acceptable limits for the given constraints. => Core Observations 1. Suffix comparison becomes easier if we reverse the strings. 2. Now the suffix matching problem transforms into a prefix matching problem, and the best data structure for efficient prefix matching is Trie / Prefix Tree. => Core Intuition 1. We insert all wordsContainer strings into the Trie in reverse order. 2. Every Trie node stores: • wordLen: smallest length of the word passing through that node • wordIdx: index of the smallest length word passing through that node. If lengths are the same, store the smaller index 3. Reaching deeper in the Trie means a longer common suffix. 4. And among all words sharing that suffix, we must return: • the smallest length word index • if lengths are the same, return the smaller index 5. So every Trie node itself stores the best possible answer for that suffix. This removes the need for any extra searching during query processing. => Edge Case If the query string does not match with any word in wordsContainer, then its longest common suffix becomes: "" (empty string) In this case: • return the index of the word with the smallest length • if multiple words have the same smallest length, return the smaller index => Complexity • Time complexity: O(N * L + M * L) • Space complexity: O(N * L) => My Detailed Solution with Dry Run + Visualization + Intuitive and Clean Code: https://lnkd.in/d75ZxJie Feel free to share your approach in the comments. #leetcode #leetcodedailycodingchallenge #java #dsa #programming #coding #softwareengineering #competitiveprogramming #algorithms #computerscience
To view or add a comment, sign in
-
-
🚀 DAY 123/150 — SORTING CHARACTERS BY FREQUENCY! 🔤📊🔥 Day 123 of my 150 Days DSA Challenge in Java and today I solved a problem that combines HashMap, sorting, and frequency analysis 💻🧠 📌 Problem Solved: Sort Characters By Frequency 📌 LeetCode: #451 📌 Difficulty: Medium 🔹 Problem Insight The task is to rearrange characters in a string based on their frequency in descending order. 👉 Characters appearing more times should come first. Example: "tree" → "eert" or "eetr" 🔹 Approach Used I used a HashMap + Priority Queue approach: 🔁 Steps: • Count frequency of each character using HashMap • Store characters in a Max Heap based on frequency • Build the answer string by repeatedly taking the highest frequency character ✔️ Efficient frequency-based sorting ⏱ Complexity Time Complexity: O(n log k) Space Complexity: O(k) 👉 k = number of unique characters 🧠 What I Learned • Frequency counting is a very common pattern in DSA • Priority Queue (Heap) helps efficiently retrieve maximum frequency elements • Combining data structures leads to cleaner solutions 💡 Key Takeaway This problem taught me: How to sort based on custom conditions Using HashMap + Heap together effectively Building optimized string manipulation solutions 🌱 Learning Insight Now I’m improving at: 👉 Solving frequency and heap-based problems 👉 Choosing the right data structure for optimization 🚀 ✅ Day 123 completed 🚀 27 days to go 🔗 Java Solution on GitHub: 👉 https://lnkd.in/gywChBFA 💡 The right data structure makes complex problems feel simple. #DSAChallenge #Java #LeetCode #HashMap #Heap #PriorityQueue #Strings #Algorithms #150DaysOfCode #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
-
🚀 DAY 138/150 — LONGEST COMMON SUFFIX QUERIES USING TRIE! 🌳🔥 Day 138 of my 150 Days DSA Challenge in Java and today I solved an advanced string problem that strengthened my understanding of Trie, suffix matching, and efficient query processing 💻🧠 📌 Problem Solved: Longest Common Suffix Queries 📌 LeetCode: #3093 📌 Difficulty: Hard 🔹 Problem Insight The task is to process queries and find the string having the longest common suffix with each query word. 👉 Brute force comparison with every string would be very expensive. 🎯 Goal: Optimize suffix searching efficiently. 🔹 Approach Used I solved this problem using a Trie Data Structure 🌳 🔁 Key Idea: • Reverse all strings • Convert suffix matching into prefix matching ⚡ Steps: • Reverse words from the container array • Insert reversed words into Trie • Reverse each query word • Traverse Trie to find the deepest matching prefix ✔️ Efficient suffix query processing ⏱ Complexity Time Complexity: Efficient due to Trie-based searching Space Complexity: Depends on Trie nodes created 🧠 What I Learned • Reversing strings can transform suffix problems into prefix problems • Trie is extremely useful for fast string matching • Hard problems often become simpler after changing perspective 💡 Key Takeaway This problem taught me: Creative usage of Trie for suffix searching How transformations simplify difficult problems Efficient query handling techniques 🌱 Learning Insight Now I’m improving at: 👉 Solving advanced Trie and string problems 👉 Recognizing transformation-based optimization patterns 🚀 ✅ Day 138 completed 🚀 12 days to go 🔗 Java Solution on GitHub: 👉 https://lnkd.in/gz2K2U9b 💡 Sometimes reversing the problem reveals the solution. #DSAChallenge #Java #LeetCode #Trie #Strings #Algorithms #DataStructures #HardProblems #150DaysOfCode #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
-
🎯 Solved LeetCode 75 — Sort Colors (Medium) At first glance, this looks like a basic sorting problem. But the real challenge? Do it in O(n) time and O(1) space — in a single pass. That's where the Dutch National Flag Algorithm by Edsger Dijkstra comes in. 💡 The Idea: Maintain 3 pointers — low, mid, high — to divide the array into 4 regions at all times: • [0..low) → all 0s • [low..mid) → all 1s • [mid..high] → unknowns • (high..n) → all 2s Scan with mid and shrink the unknown region until it disappears. ⚠️ The one trap I hit: When you swap nums[mid] with nums[high], do NOT advance mid. The swapped element is still unexamined — you need to inspect it first. ```java public void sortColors(int[] nums) { int low = 0, mid = 0, high = nums.length - 1; while (mid <= high) { if (nums[mid] == 0) { swap(nums, low++, mid++); } else if (nums[mid] == 1) { mid++; } else { swap(nums, mid, high--); // don't increment mid! } } } ``` ✅ Time: O(n) — single pass ✅ Space: O(1) — no extra memory Simple code, deep logic. That's what I love about DSA. If you're grinding LeetCode, drop a 🔥 below — let's keep each other accountable! #DSA #LeetCode #Java #CodingInterview #ProblemSolving #DutchNationalFlag #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 DAY 125/150 — BINARY SEARCH ON ROTATED ARRAY! 🔍📊 Day 125 of my 150 Days DSA Challenge in Java and today I solved a problem that strengthens understanding of Binary Search and sorted array observation 💻🧠 📌 Problem Solved: Find Minimum in Rotated Sorted Array 📌 LeetCode: #153 📌 Difficulty: Medium 🔹 Problem Insight We are given a sorted array that has been rotated at some pivot. 👉 Example: [4,5,6,7,0,1,2] 🎯 Goal: Find the minimum element in O(log n) time. 🔹 Approach Used I used a Binary Search approach: 🔁 Key Observation: • One half of the array is always sorted • The minimum element lies in the unsorted part ⚡ Logic: • Compare mid with right If nums[mid] > nums[right] → minimum lies on right side Else → minimum lies on left side including mid ✔️ Continue until left == right ⏱ Complexity Time Complexity: O(log n) Space Complexity: O(1) 🧠 What I Learned • Binary Search is not only for searching elements • Observing sorted and unsorted portions simplifies problems • Pattern recognition is very important in optimized solutions 💡 Key Takeaway This problem taught me: How to apply Binary Search creatively Identifying pivot behavior in rotated arrays Reducing brute force solutions to logarithmic time 🌱 Learning Insight Now I’m improving at: 👉 Solving Binary Search pattern problems 👉 Thinking in terms of optimization and observations 🚀 ✅ Day 125 completed 🚀 25 days to go 🔗 Java Solution on GitHub: 👉 https://lnkd.in/gdyaDxge 💡 The key to Binary Search is recognizing the pattern, not memorizing the code. #DSAChallenge #Java #LeetCode #BinarySearch #Arrays #Algorithms #150DaysOfCode #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-