Move Zeroes
Difficulty: Easy · Pattern: Two Pointers · LeetCode #283
Move all 0s in nums to the end in place, keeping the relative order of the non-zero elements. Return nothing.
Examples
text
[0, 1, 0, 3, 12] → [1, 3, 12, 0, 0]
[0] → [0]Hints
- Use a slow "write" pointer for where the next non-zero belongs.
- Swapping (instead of overwriting) avoids a second fill pass.
Approach
Scan with a fast pointer i. Whenever nums[i] is non-zero, swap it into position w and advance w. After the scan, all non-zeros sit in [0, w) in their original order, and the zeros have been swapped to the end. One pass, in place.
Complexity
Time: O(n). Space: O(1).
Python solution
def moveZeroes(nums):
w = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[w], nums[i] = nums[i], nums[w]
w += 1JavaScript solution
function moveZeroes(nums) {
let w = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) { [nums[w], nums[i]] = [nums[i], nums[w]]; w++; }
}
}