AAlgoLoopSpaced repetition for LeetCode
EASYTwo PointersLeetCode ↗

Move Zeroes

The key idea

Keep a write index for the next slot that should hold a non-zero value. Scan once; whenever you read a non-zero, place it at the write index and advance write. After the scan, every slot from write onward must be zero, so fill (or swap) the rest with zeroes. Relative order is preserved because non-zeros are copied left-to-right.

Problem

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Constraints

Examples

Input: nums=[0,1,0,3,12] Output: [1,3,12,0,0]
Input: nums=[0] Output: [0]

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Two Pointers problems