Coding interview problems › Two Pointers

↔️ Two Pointers Easy

Move Zeroes

Move Zeroes explained: a read pointer and a write pointer shift non-zero values forward in place, keeping their order, in O(n). Tested Python and live visual.

Also searched as: move all zeros to end of array · move zeroes in place

↔️

Try it live Free

Two Pointers

Watch how a pointer sweep replaces nested loops. Move Zeroes uses two pointers travelling in the same direction, one reading and one writing.

Open the playground →

The problem

Rearrange a list of integers in place so that every 0 moves to the end, while the non-zero values keep their original relative order.

Inputnums = [0, 1, 0, 3, 12]
Output[1, 3, 12, 0, 0]

The key insight

Use two pointers moving in the same direction: a read pointer that visits every element and a write pointer that marks where the next non-zero belongs. Each non-zero value is swapped into the write slot, so non-zeros pack to the front in order and zeros drift to the back.

Brute force first: Building a new list of non-zeros and padding with zeros is O(n) but not in place; repeatedly removing and appending zeros is O(n²).

Step-by-step approach

  1. Set w = 0 (next slot for a non-zero).
  2. Loop r over every index.
  3. If nums[r] != 0, swap nums[w] and nums[r], then increment w.
  4. When the loop ends, positions w onward all hold zeros.

Python solution

PYTHON 3tested
def move_zeroes(nums):
    w = 0                          # next position for a non-zero
    for r in range(len(nums)):
        if nums[r] != 0:
            nums[w], nums[r] = nums[r], nums[w]
            w += 1
    return nums

Complexity

TimeO(n)
SpaceO(1)

One pass with constant work per element and no extra list.

Common mistakes

Frequently asked questions

What is the time and space complexity of Move Zeroes?

O(n) time and O(1) extra space with the read and write pointer method.

Can I reduce the number of writes?

Swapping only when r != w avoids self-swaps. Another version copies non-zeros forward and fills the tail with zeros, which also writes each position once.

Where else is the read and write pointer idea used?

Removing duplicates from a sorted array, removing all copies of a value, and partitioning arrays all use the same same-direction two-pointer pattern.

Preparing for placements?

Take the 2-minute readiness check to find your weak patterns, then follow the placement path from DSA core to system design.

All coding interview problems More Two Pointers Two Pointers lab Placement prep guides

Problem statements on this site are written in our own words. Problem names are the common names used across interview-prep communities; BitBootcamp is an independent learning platform and is not affiliated with LeetCode or any company that asks these questions.