11. Move Zeroes
Move all 0s to the end of nums in place, keeping the relative order of the non-zero elements. Do not return anything.
Example 1
Input:
nums = [4,0,0,5,6]Output:
[4,5,6,0,0]Example 2
Input:
nums = [0]Output:
[0]Hint 1
Use a “write” pointer for where the next non-zero should go.
Approach 1: Extra array
Copy non-zeros then pad zeros.
⏱ Time O(n)💾 Space O(n)
Approach 2: Read / write pointers ✅
Swap each non-zero into the write position.
⏱ Time O(n)💾 Space O(1)
Reference solution for Read / write pointers (time O(n), space O(1)). Each solution passes every test in all four languages.
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
w = 0 # next position for a non-zero
for r in range(len(nums)):
if nums[r] != 0:
nums[w], nums[r] = nums[r], nums[w]
w += 1class Solution {
public void moveZeroes(int[] nums) {
int w = 0; // next position for a non-zero
for (int r = 0; r < nums.length; r++)
if (nums[r] != 0) { int t = nums[w]; nums[w] = nums[r]; nums[r] = t; w++; }
}
}class Solution {
public:
void moveZeroes(vector<int>& nums) {
int w = 0; // next position for a non-zero
for (int r = 0; r < (int)nums.size(); r++)
if (nums[r] != 0) swap(nums[w++], nums[r]);
}
};function moveZeroes(nums) {
let w = 0; // next position for a non-zero
for (let r = 0; r < nums.length; r++)
if (nums[r] !== 0) { [nums[w], nums[r]] = [nums[r], nums[w]]; w++; }
}Try solving it yourself first. Interviewers care more about how you explain the approach than about the finished code.
This problem is explained in the lesson Two Pointers.
Run your code to see results here.