☰ All problems

Move Zeroes

EasyArrayTwo Pointers

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.

Example 1
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.

Example 2
Input: nums = [0,-3,5]
Output: [-3,5,0]

Explanation: Only exact zeros move. The back-ordered -3 stays ahead of 5.

Example 3
Input: nums = [6,1]
Output: [6,1]

Explanation: Nothing is sold out, so the row is unchanged.

Constraints

  • nums has 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).

/**
 * @param {number[]} nums
 * @return {void} Modify nums in place.
 */
function moveZeroes(nums) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc