Move Zeroes
Given an integer array nums, shift every 0 to the end of the array while keeping the non-zero elements in their original relative order. The operation must be performed in-place, without allocating a separate copy of the array.
Input Format
Implement moveZeroes(nums). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Modify argument 1 in place. The editor compares its final value; the function return value is ignored.
Sample Input and Output
Example 1 ยท Run Sample
Input
nums = [0,1,0,3,12] Output
[1,3,12,0,0] Example 2
Input
nums = [0,0] Output
[0,0] Constraints
- 1 <= nums.length <= 10^4
- -2^31 <= nums[i] <= 2^31 - 1
Test Cases (2)
Case 1
Args: [[0,1,0,3,12]]
Expected: [1,3,12,0,0]
Case 2
Args: [[0,0]]
Expected: [0,0]
Topics
Use two pointers. A slow pointer tracks the position for the next non-zero element, while a fast pointer scans through the array. Swap non-zero elements forward to maintain relative order.
function moveZeroes(nums) {
let slow = 0;
for (let fast = 0; fast < nums.length; fast++) {
if (nums[fast] !== 0) {
[nums[slow], nums[fast]] = [nums[fast], nums[slow]];
slow++;
}
}
}Time: O(n) Space: O(1)
Saved in this browser only. Private to you.