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.
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.
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.
Step-by-step approach
- Set
w = 0(next slot for a non-zero). - Loop
rover every index. - If
nums[r] != 0, swapnums[w]andnums[r], then incrementw. - When the loop ends, positions
wonward all hold zeros.
Python solution
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 numsComplexity
One pass with constant work per element and no extra list.
Common mistakes
- Calling
nums.remove(0)andappend(0)in a loop, which is O(n²) and mutates the list while iterating. - Sorting the list, which destroys the order of the non-zero values.
- Moving the write pointer on zeros as well, which leaves zeros in the middle.
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.