Move zeroes to the end
Easy TimeO(n) SpaceO(1)
Given an array nums, move every zero to the end in place, with no second array, while the non-zero values keep their relative order exactly. So [0, 1, 0, 3, 12] becomes [1, 3, 12, 0, 0], with the zeros all together at the back.
Examples
Example 1
- Input
- nums = [0, 1, 0, 3, 12]
- Output
[1,3,12,0,0]1,3and12keep that order, and the two zeros follow them.
Example 2
- Input
- nums = [0, 0, 1]
- Output
- The one non-zero value goes to the front, and both zeros follow it.
[1,0,0]
The Code
function moveZeroes(nums) {
let write = 0;
for (let read = 0; read < nums.length; read++) {
if (nums[read] !== 0) {
nums[write] = nums[read];
write++;
}
}
while (write < nums.length) {
nums[write] = 0;
write++;
}
return nums;
}
moveZeroes([0, 1, 0, 3, 12]);Done
More like this
All two pointers examples (9) →- Two sum Walk two pointers inward until the pair sums to the target.
- Reverse array Swap the ends and step inward until the pointers meet.
- Most water Widest gap first; always move the shorter wall inward.
- Valid palindrome March inward from both ends, comparing as you go.
- 3Sum Fix one number, then two-pointer the rest toward zero.
- Sort colors Three pointers sweep 0s to the front and 2s to the back in one pass.