Move Zeroes
Problem Statement
You are given an integer array nums.
Move every 0 to the end of the array, while the non-zero elements stay in the same relative order they started in.
Do it in place β change nums directly, without making a copy of the array. The function returns nothing.
Follow-up: can you keep the number of operations small?
An integer array nums.
Nothing is returned. nums itself must end with all non-zeros first (in original order) followed by all the zeros.
The non-zeros 1, 3, 12 keep their order and move to the front. The two zeros go to the end.
Only a zero β nothing to move.
- β’ 1 β€ nums.length β€ 10^4
- β’ β2^31 β€ nums[i] β€ 2^31 β 1
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Copy non-zeros into a new array, pad with zeros, copy back
Pack non-zeros to the front with read/write, then set the tail to 0
Swap each non-zero into nums[write]; the zeros move back on their own
Make a new array. Append every non-zero in order, then append zeros until it has the same length as nums. Copy it back.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Two Pointers translate into production architectures and low-level memory mechanics.
Circular Buffer & Ring Queue
Two pointer read/write head synchronization in production memory pools.
Pointers vs References Deep Dive
Pointer arithmetic, dereferencing semantics, and memory layout behind in-place array passes.
const Correctness & East-Const
Passing read-only spans with const int* without copying buffers.