DEV Community

Tanishka V
Tanishka V

Posted on

ASSIGNMENT 13

Move All Zeros to the End (In-Place & Stable)

Rearranging arrays efficiently is a key skill in coding interviews.
Let’s solve a classic problem: moving all zeros to the end while maintaining order πŸ‘‡

πŸ“Œ Problem Statement

Given an integer array nums, move all 0s to the end of the array.

⚠️ Constraints:
Maintain the relative order of non-zero elements
Perform the operation in-place
Do not create a copy of the array
πŸ§ͺ Examples
Example 1
Input: [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Example 2
Input: [0]
Output: [0]
πŸ’‘ Optimal Approach: Two-Pointer Technique

We use a two-pointer approach to solve this efficiently.

i β†’ scans the array
j β†’ tracks position to place next non-zero element
🧠 Core Idea

πŸ‘‰ Move all non-zero elements forward
πŸ‘‰ Fill remaining positions with 0s

This ensures:

Order is preserved βœ…
No extra space is used βœ…
πŸ”„ Algorithm Steps
Initialize j = 0
Traverse array using i
If nums[i] != 0:
Swap nums[i] with nums[j]
Increment j
Continue till end
πŸ’» Python Implementation
def move_zeros(nums):
j = 0 # position for next non-zero

for i in range(len(nums)):
if nums[i] != 0:
nums[i], nums[j] = nums[j], nums[i]
j += 1
Enter fullscreen mode Exit fullscreen mode




Example usage

nums = [0, 1, 0, 3, 12]
move_zeros(nums)
print(nums)
🧾 Output
[1, 3, 12, 0, 0]
πŸ” Dry Run (Quick Insight)

For:

[0, 1, 0, 3, 12]
Move 1 β†’ front
Move 3 β†’ next
Move 12 β†’ next
Remaining filled with 0s
⚑ Complexity Analysis
Metric Value
Time Complexity O(n)
Space Complexity O(1)
🎯 Key Takeaways
Uses two-pointer technique πŸ”₯
Maintains relative order (stable) βœ…
Works in-place βœ…
Very common interview problem πŸ’‘
🏁 Conclusion

This problem highlights how a simple pointer strategy can lead to an optimal solution without extra space.

Master this pattern β€” it’s widely used in array manipulation problems πŸš€

Top comments (0)