5. Move Zeroes
Given an integer array nums, move every 0 to the end while keeping the relative order of the non-zero elements.
Do it in place, without making a copy of the array. The function returns nothing; the array itself is checked.
Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0]
Input: nums = [0] Output: [0]
Constraints
1 <= nums.length <= 10^4-2^31 <= nums[i] <= 2^31 - 1
💡 Hint 1
Keep a write pointer for where the next non-zero value should go.
💡 Hint 2
After copying the non-zero values forward, fill the rest with zeros (or swap as you go).
Try it yourself first ✎
Solutions stick better after a real attempt. Peek when you're ready.
Approach
Two pointers: write marks where the next non-zero belongs. Scan with read; whenever nums[read] is non-zero, swap it into nums[write] and advance write. Zeros naturally bubble to the end and the non-zero order is preserved.
function moveZeroes(nums) {
let write = 0;
for (let read = 0; read < nums.length; read++) {
if (nums[read] !== 0) {
[nums[write], nums[read]] = [nums[read], nums[write]];
write++;
}
}
}class Solution {
public void moveZeroes(int[] nums) {
int write = 0;
for (int read = 0; read < nums.length; read++) {
if (nums[read] != 0) {
int t = nums[write]; nums[write] = nums[read]; nums[read] = t;
write++;
}
}
}
}No submissions yet. Press Submit to run your code against every test.
/**
* @param {number[]} nums
* @return {void} Modify nums in place.
*/
function moveZeroes(nums) {
}Run your code to see results here.