Move Zeroes (LeetCode 283): Solution and Explanation
Rearrange an integer array in place so that every zero ends up at the back, while the non-zero values keep the order they started in. You may not make a copy of the array.
Watch it run step by step
Try your own input and write the code →Intuition
With a spare array this is trivial: copy the non-zero values over in order, then fill the rest with zeros. The in-place requirement rules that out. Another naive idea is to bubble each zero toward the end by swapping it with its right neighbor repeatedly, which keeps the order but costs O(n²) on an array full of zeros.
Reframe the goal. The finished array is simply the non-zero values in their original order, followed by zeros. So all you really need is a way to write the non-zero values into the front of the array in order, without losing anything. A second index, the write position, makes this possible. It marks where the next non-zero value belongs, and it only advances when a non-zero value is placed.
Scan the array with a read index i. Every time nums[i] is non-zero, swap it into nums[insert_pos] and advance insert_pos. Because the write pointer never runs ahead of the read pointer, everything between them is a zero that was skipped, so the swap sends a zero backward and pulls the next non-zero value forward. The non-zero values are placed in the same order they were read, which preserves their relative order.
When the scan ends, positions before insert_pos hold all the non-zero values in order, and every position from insert_pos onward holds a zero. Using a swap rather than an overwrite means no cleanup pass is needed to fill in the zeros afterward.
Approach: Read and write pointers with swaps
- Set
insert_pos = 0, the slot where the next non-zero value should go. - Loop
iover every index ofnums. - If
nums[i]is not zero, swapnums[insert_pos]andnums[i]. - Advance
insert_posby one after each swap. - When the loop finishes, all non-zero values sit in order at the front and the zeros fill the tail, so nothing else is needed.
Step-by-step example
nums = [0,1,0,3,12]
- At
i = 0the value is 0, so nothing happens andinsert_posstays 0. - At
i = 1the value is 1. Swap indices 0 and 1, giving [1,0,0,3,12], andinsert_posbecomes 1. - At
i = 2the value is 0, so it is skipped. - At
i = 3the value is 3. Swap indices 1 and 3, giving [1,3,0,0,12], andinsert_posbecomes 2. - At
i = 4the value is 12. Swap indices 2 and 4, giving [1,3,12,0,0], andinsert_posbecomes 3. - The scan ends with [1,3,12,0,0].
Code: Python, Java, C++
1class Solution:
2 def moveZeroes(self, nums: List[int]) -> None:
3 insert_pos = 0
4
5 for i in range(len(nums)):
6 if nums[i] != 0:
7 nums[insert_pos], nums[i] = nums[i], nums[insert_pos]
8 insert_pos += 11class Solution {
2 public void moveZeroes(int[] nums) {
3 int insertPos = 0;
4
5 for (int i = 0; i < nums.length; i++) {
6 if (nums[i] != 0) {
7 int temp = nums[insertPos];
8 nums[insertPos] = nums[i];
9 nums[i] = temp;
10 insertPos++;
11 }
12 }
13 }
14}1class Solution {
2public:
3 void moveZeroes(vector<int>& nums) {
4 int insertPos = 0;
5
6 for (int i = 0; i < nums.size(); i++) {
7 if (nums[i] != 0) {
8 swap(nums[insertPos], nums[i]);
9 insertPos++;
10 }
11 }
12 }
13};Time and space complexity
O(n)
The array is scanned once, and each element triggers at most one constant-time swap.
O(1)
Only the loop index and insert_pos are stored; all rearranging happens inside nums.
Other approaches
Overwrite then fill zeros (time O(n), space O(1))
Copy each non-zero value to nums[insert_pos] and advance, then write zeros from insert_pos to the end. It does fewer swaps but needs a second pass, and it writes to every trailing position even when they already hold zeros.
Bubble zeros to the end (time O(n²), space O(1))
Whenever you see a zero, swap it rightward step by step past non-zero values. It is correct and stable but repeats work, which makes it quadratic when there are many zeros.
Common mistakes
- Using a left and right pointer that swap zeros with values from the end. That moves zeros back quickly but scrambles the order of the non-zero values.
- Removing zeros with
nums.remove(0)inside a loop and appending them later, which is O(n²) and mutates the list while iterating over it. - Returning a new list instead of modifying
nums. The function is checked by reading the original array. - Incrementing
insert_posfor every element instead of only for non-zero ones, which turns the swap into a no-op and leaves the zeros in place.
Frequently asked questions
How do you move zeroes to the end in place?
Keep a write pointer for the next non-zero slot. Scan the array, and each time you find a non-zero value, swap it into that slot and advance the pointer. The zeros end up behind it.
Does the swap approach keep the order of non-zero elements?
Yes. Non-zero values are placed at the write pointer in the same order the scan reaches them, so their relative order never changes.
Can you minimize the number of writes?
Yes. Only swap when i != insert_pos, which skips self-swaps at the start of the array. On inputs with few zeros this cuts the writes down to the number of values that actually move.