Today’s Java DSA challenge: Sort Colors. After conquering Two-Pointer problems like moving zeroes and reversing arrays, I tackled the classic Dutch National Flag algorithm on LeetCode to sort an array of 0s, 1s, and 2s. You could easily solve this with a counting sort approach (count the 0s, 1s, and 2s, then overwrite the array in a second pass). But we can optimize this to a single pass with O(1) space using three pointers! Here is how the magic works: • low pointer: Tracks where the next 0 should go. • mid pointer: The explorer scanning through the array. • high pointer: Tracks where the next 2 should go. The Logic: • If mid finds a 0: Swap it with low, then move both low and mid forward. • If mid finds a 1: It's already in the safe middle zone, so just move mid forward. • If mid finds a 2: Swap it with high, and move high backward. (The catch? Don't move mid yet, because you still need to check the newly swapped number!) Devs: The Dutch National Flag algorithm is an absolute masterpiece. What other algorithm completely blew your mind the first time? 👇 #DSA #Java #LeetCode #SortColors
Dutch National Flag Algorithm for Sorting 0s, 1s, 2s in Java
More Relevant Posts
-
Solved Find Peak Element -> LeetCode(162) Medium, Binary Search in Java. Till now I had solved around 10-11 binary search problems. But in all of them array was always sorted , even rotated ones had at least one sorted half. So I had one strong assumption , binary search only works on sorted arrays. This problem broke that assumption completely. No sorted half, no rotation logic working. I was stuck because none of my previous patterns were fitting here. Took help from Claude. It suggested slope based thinking , if right neighbour is greater, peak is on right side, go right. If left neighbour is greater, go left. If both neighbours are smaller, current element is peak. Then I questioned > what if slope breaks in between? Claude pointed me to re-read the problem. The key insight was that array has -∞ at both ends virtually, which guarantees at least one peak always exists. Applied my own logic from there and got it accepted Then Claude showed me a cleaner version , when low < high, at the point where low == high we already have our peak. No need for extra boundary checks. That gave me a second shorter solution. Also broke my second assumption > binary search doesn't always need while(low <= high). Sometimes while(low < high) is cleaner. Two wrong assumptions fixed in one problem 🙌 Took help but questioned it, understood it, then coded it myself. Github Repo link : https://lnkd.in/grF5ACw5 **Any other wrong assumption you had about binary search? Drop it below 👇** #DSA #Java #LeetCode #BinarySearch #LearningInPublic
To view or add a comment, sign in
-
🚀 DSA in Java – Day 88 ✅ Today’s problem was all about finding the minimum distance between three equal elements in an array — and it really tested my ability to optimize brute force logic 💡 🔍 Approach I used: • Applied 3 nested loops to check all possible triplets • Optimized by skipping unnecessary comparisons using continue • Used break to stop early once a valid third element is found • Focused on minimizing (k - i) instead of full formula 💡 Key Insight: Instead of directly calculating the full distance, I realized that: 👉 Distance = 2 × (k - i) So minimizing (k - i) automatically gives the minimum distance 🚀 📈 What I learned today: • Even brute force can be improved with small optimizations • Early stopping (break) can reduce unnecessary iterations • Observing patterns in formulas helps simplify problems Some days are about solving fast, and some days are about thinking smarter — today was both 💯 Let’s keep growing consistently 💪 #DSAinJava #LeetCode #ProblemSolving #Java #CodingJourney #Consistency #100DaysOfCode
To view or add a comment, sign in
-
-
🔥 𝗗𝗮𝘆 𝟵𝟰/𝟭𝟬𝟬 — 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲 𝟭𝟱𝟯𝟵. 𝗞𝘁𝗵 𝗠𝗶𝘀𝘀𝗶𝗻𝗴 𝗣𝗼𝘀𝗶𝘁𝗶𝘃𝗲 𝗡𝘂𝗺𝗯𝗲𝗿 | 🟢 Easy | Java Marked as Easy — but the optimal solution is pure binary search brilliance. 🎯 🔍 𝗧𝗵𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 Given a sorted array, find the kth missing positive integer. Linear scan works — but can we do O(log n)? 💡 𝗧𝗵𝗲 𝗞𝗲𝘆 𝗜𝗻𝘀𝗶𝗴𝗵𝘁 At index i, the value arr[i] should be i+1 in a complete sequence. So missing numbers before arr[i] = arr[i] - 1 - i This lets us binary search on the count of missing numbers! ⚡ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 — 𝗕𝗶𝗻𝗮𝗿𝘆 𝗦𝗲𝗮𝗿𝗰𝗵 ✅ If arr[mid] - 1 - mid < k → not enough missing numbers yet, go right ✅ Else → too many missing, go left ✅ After the loop, left + k gives the exact answer 𝗪𝗵𝘆 𝗹𝗲𝗳𝘁 + 𝗸? After binary search, left is the index where the kth missing number falls beyond. left numbers exist in the array before that point, so the answer is left + k. No extra passes needed. ✨ 📊 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 ⏱ Time: O(log n) — vs O(n) linear scan 📦 Space: O(1) This is a perfect example of binary searching on a derived condition, not just a value. A real upgrade from the naive approach. 🧠 📂 𝗙𝘂𝗹𝗹 𝘀𝗼𝗹𝘂𝘁𝗶𝗼𝗻 𝗼𝗻 𝗚𝗶𝘁𝗛𝘂𝗯: https://lnkd.in/gVYcjNS6 𝟲 𝗺𝗼𝗿𝗲 𝗱𝗮𝘆𝘀. 𝗧𝗵𝗲 𝗳𝗶𝗻𝗶𝘀𝗵 𝗹𝗶𝗻𝗲 𝗶𝘀 𝗿𝗶𝗴𝗵𝘁 𝘁𝗵𝗲𝗿𝗲! 🏁 #LeetCode #Day94of100 #100DaysOfCode #Java #DSA #BinarySearch #Arrays #CodingChallenge #Programming
To view or add a comment, sign in
-
Solved LeetCode 17 – Letter Combinations of a Phone Number using backtracking in Java. Approach: Mapped each digit (2–9) to its corresponding characters using a simple array for O(1) access. Then used backtracking to build combinations digit by digit. For every digit: Pick each possible character Append → explore next digit → backtrack Key idea: Treat it like a tree of choices, where each level represents a digit and branches represent possible letters. Key learnings: Backtracking = build → explore → undo StringBuilder helps avoid unnecessary string creation Problems like this are about systematic exploration of choices Time Complexity: O(4^n * n) Space Complexity: O(n) recursion stack + output Consistent DSA practice is strengthening pattern recognition day by day. #Java #DSA #Backtracking #LeetCode #CodingInterview #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Mastering Java Through LeetCode 🧠 Day 32 Today I solved an Easy-level Tree problem that strengthened my understanding of Recursion + Depth Calculation — a fundamental concept for tree-based problems 📌 LeetCode Problem Solved: Q.104. Maximum Depth of Binary Tree 💭 Problem Summary: Given a binary tree, the task is to find the maximum depth — i.e., the number of nodes along the longest path from root to leaf. 🧠 Approach (Optimal): Instead of iterating level by level, I used a clean recursive approach: ✔️ If node is null → return 0 ✔️ Recursively calculate left subtree depth ✔️ Recursively calculate right subtree depth ✔️ Return 1 + max(left, right) ⚡ Key Learning: Recursion makes tree problems much simpler when you think in terms of “what should each function return for a node?” Complexity: Time: O(n) Space: O(h) Takeaway: Tree problems become easier once you master recursion and start recognizing patterns. Consistency is the key — showing up every day #Day32 #LeetCode #Java #DSA #CodingJourney #Recursion #BinaryTree #100DaysOfCode #SoftwareEngineering
To view or add a comment, sign in
-
-
Leetcode Practice - 16. 3Sum Closest The problem is solved using JAVA Given an integer array nums of length n and an integer target, find three integers at distinct indices in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Example 1: Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). Example 2: Input: nums = [0,0,0], target = 1 Output: 0 Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0). Constraints: 3 <= nums.length <= 500 -1000 <= nums[i] <= 1000 -104 <= target <= 104 #LeetCode #Java #CodingPractice #ProblemSolving #DSA #Array #DeveloperJourney #TechLearning
To view or add a comment, sign in
-
-
📝 𝗧𝗵𝗲 "𝗛𝗼𝗺𝗲" 𝗳𝗼𝗿 𝗠𝘆 𝗟𝗼𝗴𝗶𝗰: 𝗪𝗵𝘆 𝗜 𝗖𝗵𝗼𝘀𝗲 𝗝𝗮𝘃𝗮 𝟮𝟲+ I’ve spent a lot of time exploring different ecosystems—C#, Python, Go, and Rust. They are all incredible tools, and I have deep respect for the engineers who build with them. Every language offers a unique perspective on how to solve problems. But for my own work, I’ve found that my brain simply "clicks" with Java 26+. It isn't about one being "better" than the other; it’s about finding the right 𝗶𝗻𝘁𝗲𝗴𝗿𝗶𝘁𝘆 for the way I think. Here is why I’ve decided to make Java my primary focus: ● 𝗧𝗵𝗲 𝗖𝗹𝗮𝗿𝗶𝘁𝘆 𝗼𝗳 𝘁𝗵𝗲 𝗦𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲: I find peace in Java’s explicit nature. The syntax feels durable and balanced. To me, the "verbosity" isn't noise—it’s the clear definition of the system’s perimeter. ● 𝗧𝗵𝗲 𝗘𝘃𝗼𝗹𝘂𝘁𝗶𝗼𝗻 𝗼𝗳 𝘁𝗵𝗲 𝗝𝗩𝗠: Seeing the progress from Java 21 to Java 26 has been inspiring. Features like Virtual Threads and advanced Pattern Matching have turned the JVM into a modern, heavyweight forge that handles data exactly how I envision it. ● 𝗔 𝗣𝗲𝗿𝘀𝗼𝗻𝗮𝗹 𝗦𝘁𝗮𝗻𝗱𝗮𝗿𝗱: We all look for a tool that feels like "home." For me, Java provides the right weight and the right grip to implement the Data-Oriented principles I value most. I'm grateful for everything I learned from other languages, but for the projects I’m building now, I’m staying with the JVM. It’s where I feel I can do my best work. 🌊🛡️ #Java26 #SoftwareArchitecture #JVM #DataOrientedProgramming #CleanCode #SystemDesign #EngineeringExcellence
To view or add a comment, sign in
-
-
🚀 Solved “Detect Cycles in 2D Grid” (LeetCode 1559) Worked on a classic graph problem and implemented an efficient DFS-based solution in Java. 🔍 Key idea: Treat the grid as an undirected graph and detect cycles by: Traversing only same-character neighbors Tracking the parent cell to avoid false cycles Identifying a cycle when visiting an already visited node (not parent) ⚡ Insight: Using a recursion stack (like in directed graphs) gives wrong results here — parent tracking is the correct approach. ⏱ Complexity: Time: O(m × n) Space: O(m × n) 📌 Also added a clean, documented version to my GitHub with test cases. 🔗 LeetCode: https://lnkd.in/d6CKa-BN 🔗 GitHub: https://lnkd.in/gnEfmGAg #Java #DSA #GraphAlgorithms #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
Day 94 - LeetCode Journey Solved LeetCode 35: Search Insert Position in Java ✅ Classic Binary Search problem that tests your fundamentals. Instead of just finding the element, the twist is to return the correct insert position if it’s not present. The key idea is simple: keep narrowing the search space and finally return low, which represents the right position. Clean logic, high impact 💡 Key takeaways: • Strong grip on Binary Search fundamentals • Understanding search space boundaries • Returning correct insertion index • Writing efficient O(log n) solutions ✅ All test cases passed ⚡ O(log n) time and O(1) space Mastering basics like Binary Search is what builds real problem-solving strength 🔥 #LeetCode #DSA #Java #BinarySearch #ProblemSolving #CodingJourney #InterviewPrep #Consistency #100DaysOfCode
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
I have an question what platform you're using to learn and master DSA