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
- 1 <= nums.length <= 10^4
- -2^31 <= nums[i] <= 2^31 - 1
- Follow-up: could you minimize the total number of operations done?
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
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Two Pointers problems
- 3SumMEDIUM
- 4SumMEDIUM
- Concatenation of ArrayEASY
- Container With Most WaterMEDIUM
- Is SubsequenceEASY
- Merge Sorted ArrayEASY
- Merge Strings AlternatelyEASY
- Next PermutationMEDIUM
- Remove Duplicates from Sorted ArrayEASY
- Remove Duplicates from Sorted Array IIMEDIUM
- Remove ElementEASY
- Reverse StringEASY