Move Zeroes Using Two Pointers

Move all zeroes to the end of an array while keeping the order of non-zero elements, using two pointers in O(n) time and O(1) space.

Problem Statement

Given an array nums, move all 0s to the end while keeping the relative order of the non-zero elements. Do it in place without making a copy.

Example

Input:  nums = [0,1,0,3,12]
Output: [1,3,12,0,0]

Two Pointer Approach

Keep a last write pointer for the next non-zero slot. Scan with a read pointer; each time you see a non-zero value, write it at last and increment last. Finally, fill the remaining positions with zeroes.

Complexity

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

Solution Code

Python

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

Java

void moveZeroes(int[] nums) {
    int last = 0;
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] != 0) nums[last++] = nums[i];
    }
    while (last < nums.length) nums[last++] = 0;
}

C++

void moveZeroes(vector<int>& nums) {
    int last = 0;
    for (int i = 0; i < (int)nums.size(); i++) {
        if (nums[i] != 0) nums[last++] = nums[i];
    }
    while (last < (int)nums.size()) nums[last++] = 0;
}

Key Takeaways

  • Order is preserved because we copy non-zeros left to right.
  • A single swap-based variant also works and avoids the second loop.
  • This is the same slow/fast write pattern as Remove Element.
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.