DEV Community

Navin S
Navin S

Posted on

๐Ÿš€ Move Zeroes (In-Place & Efficient)

The Move Zeroes problem is a classic array manipulation question where the goal is to rearrange elements efficiently while preserving order.


๐Ÿ“Œ Problem Statement

Given an array nums, move all 0s to the end while maintaining the relative order of non-zero elements.

The operation must be done in-place without using extra space.


๐Ÿ” Examples

Example 1:
Input: [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]

Example 2:
Input: [0]
Output: [0]


๐Ÿง  Intuition

We need to:

  • Keep all non-zero elements in the same order
  • Move all zeros to the end

๐Ÿ‘‰ This can be done efficiently using a two-pointer approach


๐Ÿ”„ Approach (Optimal Two-Pointer Method)

Step-by-Step:

  1. Initialize a pointer j = 0
    (this will track position for next non-zero element)

  2. Traverse the array:

  • If nums[i] != 0:

    • Swap nums[i] with nums[j]
    • Increment j

๐Ÿ’ป Python Code

def move_zeroes(nums):
j = 0

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

return nums
Enter fullscreen mode Exit fullscreen mode

print(move_zeroes([0, 1, 0, 3, 12]))


๐Ÿงพ Dry Run

For: nums = [0, 1, 0, 3, 12]

Step-by-step:

  • i = 0 โ†’ 0 โ†’ skip
  • i = 1 โ†’ 1 โ†’ swap with index 0 โ†’ [1, 0, 0, 3, 12]
  • i = 2 โ†’ 0 โ†’ skip
  • i = 3 โ†’ 3 โ†’ swap with index 1 โ†’ [1, 3, 0, 0, 12]
  • i = 4 โ†’ 12 โ†’ swap with index 2 โ†’ [1, 3, 12, 0, 0]

Final Output: [1, 3, 12, 0, 0]


โšก Complexity

Time Complexity: O(n)
Space Complexity: O(1)


๐Ÿ”ฅ Why This Works

  • Maintains order of non-zero elements
  • Minimizes unnecessary swaps
  • Uses constant extra space

โš ๏ธ Follow-Up Optimization

To minimize operations:

๐Ÿ‘‰ Only swap when i != j
This avoids swapping an element with itself.


๐Ÿ Conclusion

Move Zeroes is a simple yet powerful problem that teaches:

  • Two-pointer technique
  • In-place array manipulation
  • Efficient traversal

Mastering this helps in many real-world and interview scenarios.

Top comments (0)