Move Zeroes
A warehouse dashboard shows one stock count per product, in a fixed order, in the array nums. Products that are sold out (a count of exactly 0) should sink to the end of the row, while all other products stay in the same relative order. A negative count means the product is back-ordered; it is not sold out, so it does not move to the end.
Rearrange nums in place, without building a second array. The function returns nothing; the tests inspect nums after the call.
Input: nums = [0,9,0,0,4,7] Output: [9,4,7,0,0,0]
Explanation: The three sold-out products move to the end, and 9, 4, 7 keep their order.
Input: nums = [0,-3,5] Output: [-3,5,0]
Explanation: Only exact zeros move. The back-ordered -3 stays ahead of 5.
Input: nums = [6,1] Output: [6,1]
Explanation: Nothing is sold out, so the row is unchanged.
Constraints
numshas between 1 and 10^4 entries.- Each entry fits in a 32-bit signed integer.
💡 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.