Interview preparation
Move Zeroes
1Problem statement
Given an integer array nums, move all 0s to the end while keeping the relative order of the non-zero elements. Do it in place.
2Examples
3Constraints
- 1 ≤ nums.length ≤ 10⁴
- −2³¹ ≤ nums[i] ≤ 2³¹ − 1
4Approaches
Approach 1
Brute Force
Copy non-zeros into a new array, then fill the rest with zeros and copy back.
Approach 2
Better: Overwrite then fill
Write non-zeros forward with an index, then fill the tail with zeros.
Approach 3
Optimal: Two-pointer swap
Pointer `write` marks the next slot for a non-zero; swap each non-zero into it. Minimises writes.
5Code (optimal approach)
Complete programs that print the example outputs — verified in JavaScript, Python, Java and Go.
6Complexity
Time
O(n)
Space
O(1)
7Visual walkthrough
- 1.write = 0
- 2.read 0 → skip
- 3.read 1 → swap into 0 → [1, 0, 0, 3, 12], write = 1
- 4.read 3 → swap → [1, 3, 0, 0, 12], write = 2
- 5.read 12 → swap → [1, 3, 12, 0, 0]
Related visualization (Reverse an Array) — shows the core data-structure operations this solution relies on:
Reverses an array in place with two pointers: swap the outermost pair, move both pointers inward, and stop when they meet.