Move Zeroes
Easy · Two Pointers · Array · Two Pointers
Problem
Shift every zero in nums to the end while keeping the order of the non-zero values. Modify the array in place — do not build and return a new one.
Examples
Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0]
1, 3 and 12 keep their relative order.
Input: nums = [0] Output: [0]
Constraints
- 1 <= len(nums) <= 10^4
- -2^31 <= nums[i] <= 2^31 - 1
- The array must be changed in place
Approaches
- Write cursor, then fill — time O(n), space O(1)
Related problems
Start free on Cariara · Coding problems · System design studio