☰ All problems

5. Move Zeroes

EasyArrayTwo Pointers

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.

Example 1
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2
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).

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

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