Move Zeroes to End Visualization & Animation
Moves all zeros to the end while preserving relative order of non-zero elements in-place; O(n) time, O(1) space.
## What is it?
Move all zeros in an array to the end while maintaining the relative order of non-zero elements. Done in-place in a single pass.
## How it works
- Use a slow pointer `insertPos = 0` tracking where the next non-zero element should go
- Iterate with `i` from 0 to n-1:
- If `arr[i] != 0` → place it at `insertPos`, advance `insertPos`
- After the loop, fill positions from `insertPos` to `n-1` with zeros
**Alternative (swap-based):**
- Swap `arr[i]` and `arr[insertPos]` whenever `arr[i] != 0`, then advance `insertPos`
## When to use
- In-place array cleanup with a "gather non-matching elements" pattern
- Template for "move all elements satisfying condition to one end"
## Key Points
- O(n) time, O(1) space
- Maintains relative order of non-zero elements (stable)
- The fill step is necessary in the copy approach; the swap approach avoids it but does more writes
Category: algorithms
Difficulty: beginner
- two-pointers
Time Complexity: O(n)
Space Complexity: O(1)
View Move Zeroes to End VisualizationMove Zeroes to End
beginnerMoves all zeros to the end while preserving relative order of non-zero elements in-place; O(n) time, O(1) space.
j0
i0
0
[0]1
[1]0
[2]3
[3]12
[4]0
[5]5
[6]2
[7]0
[8]4
[9]6non-zero4zeros
Initialising pointers…
Non-zero value
Zero value
j — insertion pointer
i — scan pointer
Init: insertPos=0, i=0. Array: [0, 1, 0, 3, 12, 0, 5, 2, 0, 4]
1 / 22