Solved "Sort Colors" on LeetCode I remember solving this before as “Sort 0/1/2”. This time I tried from memory, then checked my old notes to fix a missing detail. Problem : Sort an array of 0s, 1s, and 2s in-place in a single pass & O(1) space. Approach — Dutch National Flag Algorithm We use 3 pointers: • low → for 0s which starts from 0th index. • mid → for current element • high → for 2s which starts from last index. Logic: If Element is 0 : • It belongs to the front → swap with `low` • We increase both `low` and `mid` Because we are sure the swapped element is 1 (already checked earlier) If Element is 2 : • It belongs to the end → swap with `high` • Only decrease `high` Because the swapped element might be 0 or 1, so we must recheck this index → don’t move mid • If Element is 1 : just move mid ahead This gradually pushes all 0s to the left and 2s to the right #LearnInPublic #LeetCode #Java #PlacementPrep #DSA Code (Java):
Solved "Sort Colors" problem on LeetCode using Dutch National Flag Algorithm
More Relevant Posts
-
✨ Day 58 of 100: Partition List ✨ Today’s challenge was LeetCode 86 – Partition List 🧩 Problem Statement: Given the head of a linked list and a value x, partition it such that all nodes with values less than x come before nodes with values greater than or equal to x. The relative order of nodes in each partition should remain the same. 💡 Key Takeaways: 🔹 Practiced two-pointer technique to maintain separate lists for nodes < x and ≥ x. 🔹 Improved understanding of in-place linked list manipulation. 🔹 Strengthened grasp of dummy node usage to simplify edge cases. 🧠 Approach: 1️⃣ Create two dummy lists – one for smaller nodes and one for greater/equal nodes. 2️⃣ Traverse the original list and link nodes accordingly. 3️⃣ Finally, connect the smaller list’s tail to the head of the greater list. 🔥 Learning: This problem reinforced how clean list partitioning can be done efficiently with dummy nodes and careful pointer handling — all in O(n) time and O(1) extra space! #100DaysOfCode #Day58 #LeetCode #Java #LinkedList #CodingChallenge #ProblemSolving #DSA #PartitionList
To view or add a comment, sign in
-
-
🔹 Day 47: Find Pivot Index (LeetCode #724) 📌 Problem Statement: Given an array of integers nums, the pivot index is the index where the sum of all numbers to the left is equal to the sum of all numbers to the right. If no such index exists, return -1. If multiple exist, return the leftmost one. ✅ My Approach: I first calculated the total sum of the array, then iterated through each element keeping track of the left sum. At each index, I checked whether left sum == total sum - left sum - current element. If true, that index is the pivot index. 📊 Complexity: Time Complexity: O(n) Space Complexity: O(1) ⚡ Submission Stats: Runtime: 0 ms (Beats 100%) Memory: 45.41 MB (Beats 66.27%) 💡 Reflection: This problem strengthened my understanding of prefix sums and efficient single-pass array traversal. A clean and optimized logic! 💪 #LeetCode #Java #Arrays #PrefixSum #100DaysOfCode #Day47
To view or add a comment, sign in
-
-
💻 LeetCode Daily Challenge - #3217. Delete Nodes From Linked List Present in Array ❓ Problem statement: You are given an array of integers nums and the head of a linked list. Return the head of the modified linked list after removing all nodes from the linked list that have a value that exists in nums. 🧠 Intuition: While traversing linked list, We need to find out if a element is present in nums array efficiently. Add all nums to a SET so we can have constant lookup time to finding if a number is in nums. ⚙️ Approach: 1. Create a hashset to store elements of nums array. 2. We might have to remove the head element so make a dummy node whose next node is head. 3. Make two nodes prev which points to dummy node & curr which points to head. 4. Traverse linked list until curr becomes null -> If curr node value is in the set of nums remove it by setting next node of prev to curr's next. 5. Return dummy node's next node. ⏳ Time Complexity: O(n + m) -> n: size of nums array, m: size of linked list. 📦 Space complexity: O(n) -> HashSet of size n Github: https://lnkd.in/gRbRrJ5P #Java #DSA #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
-
DSA Practice – Day 66 🚀 Problem: Merge Two Sorted Linked Lists (LeetCode 21) ✨ Brute Force Approach 1. Traverse both linked lists and store all values in an ArrayList. 2. Sort the ArrayList. 3. Create a new linked list using the sorted values. Time Complexity: O((n+m) log(n+m)) Space Complexity: O(n+m) (because we used extra array) ✨ Optimal Approach We take advantage of the fact that both lists are already sorted. Steps: 1. Use two pointers, each pointing to the head of the two lists. 2. Compare the values and keep attaching the smaller value to the result list. 3. Move the pointer forward in the list from which the smaller value was taken. 4. If one list finishes, attach the remaining part of the other list. Time Complexity: O(n + m) Space Complexity: O(1) (no extra array used, we just rearrange pointers) 🌟 Key Idea Instead of sorting again, we merge directly like in the merge step of Merge Sort. #Day66 #LinkedList #DSA #Java #LeetCode #Placements
To view or add a comment, sign in
-
-
DSA Practice – Day 57 🚀 Problem: Delete the Middle Node of a Linked List (LeetCode 2095) Problem Statement: Given the head of a linked list, delete its middle node, and return the modified list. If there’s only one node, return null. ⚡ Brute Force Approach: Traverse the list once to count the total nodes. Find the middle index using count / 2. Traverse again to reach the node just before the middle. Delete the middle node by updating the links. Time Complexity: O(2n) ≈ O(n) Space Complexity: O(1) ⚡ Optimal Approach (Two Pointers): Use slow and fast pointers. Move fast twice as fast as slow. When fast reaches the end, slow will be at the middle. Delete the middle node by linking prev.next = slow.next. Time Complexity: O(n) Space Complexity: O(1) ✨ What I Learned: Two-pointer technique makes linked list problems efficient and elegant. Traversal count helps understand index-based operations clearly. #Day57 #DSA #Java #LinkedList #LeetCode #ProblemSolving #CodingJourney #PlacementPrep
To view or add a comment, sign in
-
-
#Day-70) LeetCode #3234 – Count Substrings With Dominant Ones Just solved an interesting binary string problem where a substring is considered dominant if the number of 1s is greater than or equal to the square of the number of 0s. 🔍 Challenge: Efficiently count all such substrings in a given binary string. 🧠 My Approach (Java): Used a prefix sum array to track the balance between 1s and 0s Explored substring ranges with a smart condition check Focused on clean logic and edge case handling 📈 Why it matters: This problem blends math with string manipulation and highlights how preprocessing (like prefix sums) can drastically reduce brute-force overhead. 📎 Code snippet attached — open to feedback or alternate strategies! #LeetCode #Java #DSA #BinaryStrings #ProblemSolving #CodingInPublic #TechJourney
To view or add a comment, sign in
-
-
23/30 days✅ Solved LeetCode Problem : #70 – Climbing Stairs The challenge was to determine how many distinct ways one can reach the top of a staircase with n steps, where at each step you can either climb 1 or 2 steps. The logic behind the problem is similar to the Fibonacci sequence, where each state depends on the sum of the previous two states. I implemented the solution in Java, using an iterative approach with three variables to optimize space complexity. Instead of using recursion or an array, the approach updates values in constant space (O(1)) while maintaining linear time complexity (O(n)). Here’s the logic in brief: Initialize a = 0, b = 1, and c = 1. For each step, compute c = a + b, then shift values forward (a = b, b = c). Return c as the total number of distinct ways to reach the top. #LeetCode #Java #DynamicProgramming #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🚀#PostLog34 🔹 LeetCode 1901: Find a Peak Element II Problem was focused on efficiently finding a peak element in a 2D grid — one that’s greater than all its adjacent cells (top, bottom, left, and right). 💡 Concept learned: Instead of scanning the entire grid, a binary search on columns helps reduce time complexity to O(m log n). For each middle column, find the global maximum element, then decide which side to move based on neighboring values — simple yet powerful divide-and-conquer logic. ✅ 58/58 test cases passed ⚡ Runtime: 0ms | Beats 100% of Java submissions Each problem reinforces how algorithmic thinking and optimization go hand-in-hand — step by step toward sharper logic and cleaner solutions. #LeetCode #Java #DSA #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
#Day-56) LeetCode #3217: Delete Nodes From Linked List Present in Array Today’s medium-level challenge was a classic linked list cleanup with a twist—removing nodes whose values appear in a separate array. I leaned on a HashSet for O(1) lookups and handled edge cases like head deletion with precision. 🔧 Problem: Given an array `nums` and a linked list `head`, remove all nodes from the list whose values are in `nums`. 💡 Approach: - Store `nums` in a HashSet for fast lookup. - Traverse the list using `prev` and `curr` pointers. - Carefully handle head node removal. - Return the updated head. 📌 Language: Java 📈 Time Complexity: O(n + m) 📦 Space Complexity: O(m) #LeetCode #Java #LinkedList #DSA #CodingChallenge #ProblemSolving #PranshuCodes Aditya Gupta Arjit Singh
To view or add a comment, sign in
-
Explore related topics
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