🚀 DSA Practice – Move All Zeros to the End of an Array Today I tackled a common array manipulation problem: Moving all zeros to the end while maintaining the relative order of non-zero elements. 📌 Problem Statement: Given an array arr[], push all the zeros to the end of the array. The relative order of the non-zero elements must remain the same. 🧠 My Approach: 1️⃣ Initialize a pointer count to keep track of the position where the next non-zero element should be placed. 2️⃣ Traverse the array. Every time a non-zero element is encountered, swap it with the element at the count index and increment count. 3️⃣ By the end of the single traversal, all non-zero elements are at the front, and zeros are naturally pushed to the back. ⚙️ Example: Input: [3, 5, 0, 0, 4] Output: [3, 5, 4, 0, 0] 📊 Complexity: Time Complexity: $O(n)$ (Single pass through the array) Auxiliary Space: $O(1)$ (In-place swap, no extra space used) 💻 Language Used: Python This problem is a classic example of the Two-Pointer technique, which is essential for writing efficient, in-place algorithms. Keeping the momentum going as I prepare for upcoming placements! 💪 #DSA #Python #CodingPractice #ProblemSolving #Arrays #TwoPointers #LearningInPublic
Move Zeros to End of Array with Python
More Relevant Posts
-
🚀 Solved a LeetCode Problem – Running Sum (Prefix Sum Concept) Today I solved a problem based on the Running Sum / Prefix Sum concept. 🔍 Problem Statement: Given an array, compute a new array where each element at index i represents the sum of all elements from index 0 to i. 💡 My Approach: Instead of recalculating the sum for every index (which would be inefficient), I used an incremental approach: I initialized a result list with the first element. Then, I iterated through the array starting from index 1. At each step, I updated the current element by adding the previous cumulative sum: 👉 Current element = Current value + Previous running sum I stored each updated value in the result list. This way, I reused previously computed results instead of recomputing sums again and again. ⚡ Why this is efficient? Each element is processed only once. No nested loops are used. Avoids redundant calculations. ⏱️ Complexity Analysis: Time Complexity: O(n) → Single pass through the array Space Complexity: O(n) → Extra list used to store results 📌 Key Learning: This problem helped me understand the importance of Prefix Sum technique, which is widely used in problems involving range sums, subarrays, and optimizations. 💻 Code: class Solution: def runningSum(self, nums: List[int]) -> List[int]: res=[] res.append(nums[0]) for i in range(1,len(nums)): nums[i]=nums[i]+nums[i-1] res.append(nums[i]) return res #100DaysOfCode #Python #DSA #CodingJourney #PrefixSum #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 25 of Consistency | #75DaysLeetCodeChallenge 🧠 Today’s Problem: Search a 2D Matrix (#74) 💡 Key Learning: This problem teaches how to apply binary search on a 2D matrix by treating it as a flattened sorted array. It’s all about visualizing the structure differently. ⚡ Approach: First apply binary search on rows to find the potential row Check range using first and last element of each row Once row is identified → apply binary search on that row Return true if target found, else false 🧠 Why this works: Matrix follows sorted properties row-wise and across rows Binary search efficiently reduces search space Achieves optimal time complexity → O(log(m × n)) 🔥 Result: ✔️ Runtime: 0 ms (Beats 100%) 📈 This is a classic problem combining matrix + binary search, frequently asked in interviews. A big thanks to Shivam Singh, Nikhil Yadav & Akshat Tiwari for this amazing challenge 🙌 Consistency is compounding. Keep going. 💪 #Day25 #LeetCode #DSA #CodingJourney #100DaysOfCode #Python #BinarySearch #Consistency
To view or add a comment, sign in
-
-
✅ Day 74 of 100 Days LeetCode Challenge Problem: 🔹 #653 – Two Sum IV: Input is a BST 🔗 https://lnkd.in/g9vDFKMA Learning Journey: 🔹 Today’s problem required checking whether there exist two nodes in a Binary Search Tree whose values sum to k. 🔹 I performed a Depth-First Search (DFS) traversal using a stack to visit all nodes of the tree. 🔹 While traversing, I stored each node’s value in a list. 🔹 Then I used a hash set to track visited values and checked whether the complement (k - value) already exists. 🔹 If the complement is found, it means two numbers sum to k, so the function returns True. Concepts Used: 🔹 Depth-First Search (DFS) 🔹 Stack-based Tree Traversal 🔹 Hash Set for Fast Lookup 🔹 Two Sum Pattern Key Insight: 🔹 The classic Two Sum approach works well after collecting values from the BST. 🔹 Using a set allows O(1) lookup, making it efficient to check complements during iteration. Complexity: 🔹 Time: O(n) 🔹 Space: O(n) #LeetCode #Algorithms #DataStructures #CodingInterview #100DaysOfCode #SoftwareEngineering #Python #ProblemSolving #LearningInPublic #TechCareers
To view or add a comment, sign in
-
-
LeetCode Journey – Day 6 Today I solved the Encode and Decode Strings problem At first glance, it looks simple… but the real challenge is handling edge cases where strings may contain special characters like #. My Approach (Optimal Solution): Instead of using delimiters (which can fail), I used length-based encoding. Each string is stored as: length + "#" + string Example: ["neet", "code"] → "4#neet4#code" This ensures: No ambiguity Works with any characters Efficient encoding & decoding Key Learning: Never rely on simple separators when data itself can contain them. Using length prefixing makes the solution robust and interview-ready. Complexity: Time: O(n) Space: O(n) Another step forward in my DSA journey! #LeetCode #DSA #CodingJourney #Python #ProblemSolving #Day6 #TechLearning
To view or add a comment, sign in
-
-
✅ Day 76 of 100 Days LeetCode Challenge Problem: 🔹 #75 – Sort Colors 🔗 https://lnkd.in/gpH9fEJu Learning Journey: 🔹 Today’s problem required sorting an array containing only 0s, 1s, and 2s (representing colors) in-place without using built-in sort. 🔹 I implemented a selection sort approach, where for each index, I searched for the minimum element in the remaining array. 🔹 Once found, I swapped it with the current position to gradually build the sorted array. 🔹 This ensured the array was sorted in ascending order (0 → 1 → 2). Concepts Used: 🔹 Selection Sort 🔹 In-place Swapping 🔹 Nested Iteration Key Insight: 🔹 Even though the problem has an optimal linear-time solution (Dutch National Flag algorithm), a simple sorting approach like selection sort still works correctly. 🔹 Iteratively placing the smallest remaining element ensures correctness, though not optimal efficiency. Complexity: 🔹 Time: O(n²) 🔹 Space: O(1) #LeetCode #Algorithms #DataStructures #CodingInterview #100DaysOfCode #SoftwareEngineering #Python #ProblemSolving #LearningInPublic #TechCareers
To view or add a comment, sign in
-
-
✅ Day 87 of 100 Days LeetCode Challenge Problem: 🔹 #2840 – Check if Strings Can be Made Equal With Operations II 🔗 https://lnkd.in/gY73RBb5 Learning Journey: 🔹 Today’s problem extended the previous one, allowing swaps between indices where the difference is even. 🔹 I observed that this again partitions the string into two independent groups: • Even indices (0, 2, 4, …) • Odd indices (1, 3, 5, …) 🔹 I extracted characters from even and odd positions separately for both strings. 🔹 Then, I sorted these groups and compared them between s1 and s2. 🔹 If both even-index groups and odd-index groups match, the strings can be made equal. Concepts Used: 🔹 String Manipulation 🔹 Index Grouping (Parity-based) 🔹 Sorting 🔹 Greedy Observation Key Insight: 🔹 Since swaps are allowed only between indices with even distance, characters can only move within their parity group. 🔹 Therefore, the problem reduces to checking if both parity groups have identical character distributions. Complexity: 🔹 Time: O(n log n) 🔹 Space: O(n) #LeetCode #Algorithms #DataStructures #CodingInterview #100DaysOfCode #SoftwareEngineering #Python #ProblemSolving #LearningInPublic #TechCareers
To view or add a comment, sign in
-
-
🚀 Day 13 of Consistency | #75DaysLeetCodeChallenge 🧠 Today’s Problem : Container With Most Water (#11) 💡 Key Learning: This problem strengthens understanding of the two-pointer optimization technique, where maximizing area depends on width & minimum height. ⚡ Approach: Use two pointers → left (l) at start & right (r) at end →Calculate area = (r - l) * min(height[l], height[r]) →Update max area →Move the pointer with smaller height (to try increasing area) 🧠 Why this works: Eliminates brute force O(n²) → optimized to O(n) Greedy movement ensures better area possibilities No extra space → O(1) 🔥 Result : ✔️ Runtime: 57 ms (Beats 60.95%) 📈 Problems like this build strong intuition for optimization & greedy thinking. Consistency is compounding. Keep going. 💪 #Day13 #LeetCode #DSA #CodingJourney #100DaysOfCode #Python #TwoPointers #Consistency
To view or add a comment, sign in
-
-
🚀 Day 28 of Problem Solving Journey Today, I worked on an interesting problem: Group Anagrams 🔍 Problem Statement: Given an array of strings, group the anagrams together. Anagrams are words that have the same characters but arranged differently. 💡 Approaches I explored: ✅ Approach 1: Character Frequency Count (Optimized) Used a fixed-size array (26 letters) to count character occurrences Converted the count into a tuple to use as a dictionary key Achieved an efficient time complexity of O(n * k) ✅ Approach 2: Sorting Strings Sorted each string and used it as a key Simple and intuitive approach Time complexity: O(n * k log k) 📌 Key Learning: Understanding how hashing works with different representations (frequency vs sorted string) helps in optimizing solutions. ⚡ Takeaway: There are always multiple ways to solve a problem, but choosing the most efficient one makes a difference in real-world applications and interviews. 💻 Tech Used: Python | HashMap | Arrays #Day28 #ProblemSolving #Python #DataStructures #Algorithms #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 26 of Consistency | #75DaysLeetCodeChallenge 🧠 Today’s Problem: Find Minimum in Rotated Sorted Array (#153) 💡 Key Learning: This problem builds deeper intuition for binary search on rotated arrays, where the sorted order is partially disturbed but still exploitable. ⚡ Approach: Use binary search to identify the unsorted portion Maintain left and right pointers If current subarray is already sorted → update result and break Find mid and update minimum If mid element ≥ left → move right side Else → move left side Keep updating the minimum element 🧠 Why this works: At least one half of the array is always sorted Binary search helps eliminate half search space each step Efficiently finds minimum in O(log n) time 🔥 Result: ✔️ Runtime: 0 ms (Beats 100%) 📈 This is a classic binary search variation and very important for mastering rotated array problems in interviews. A big thanks to Shivam Singh, Nikhil Yadav & Akshat Tiwari for this amazing challenge 🙌 Consistency is compounding. Keep going. 💪 #Day26 #LeetCode #DSA #CodingJourney #100DaysOfCode #Python #BinarySearch #Consistency
To view or add a comment, sign in
-
-
Non-overlapping Intervals (LeetCode 435) - Medium Today, I tackled a classic interval problem that requires a slightly different strategy. The goal was to find the minimum number of intervals to remove to make the rest non-overlapping. While most interval problems are solved by sorting by start time, this one taught me the power of sorting by end time to make optimal choices. Key Learnings: *Greedy Strategy: To keep as many intervals as possible, it's best to pick the ones that end the earliest. This leaves the maximum possible room for the intervals that follow. *End-Time Sorting: Sorting by end time allows us to always pick the interval that finishes first, which is the 'Greedy' choice for this problem. *Overlap Detection: Once sorted, if a new interval starts before the previously selected one ends, we know it must be removed to avoid a conflict. Complexity: ⏱️ Time Complexity: O(N log N) 📂 Space Complexity: O(1) #LeetCode #CodingJourney #Blind75 #SDEPrep #DataStructures #Python #GreedyAlgorithms #ProblemSolving #TechCareer
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
Great practice problem! Maintaining the relative order while moving zeros is a good example of stable in-place operations. It’s interesting how the same technique is often used in other array partitioning problems as well.