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
Time Complexity: O(n)
Space Complexity: O(1)
View Move Zeroes to End Visualization