Move Zeroes — Discovering a Two-Pointer Algorithm From Scratch
LeetCode 283: from moving cells by hand to a loop invariant, with my accepted solution and a cleaner version derived step by step.
How do you go from “I can do this by hand” to a two-pointer algorithm you could rebuild on your own?
This article does not start with the answer. It starts with what the problem asks, lets you solve small cases with your own hands, and only then turns your moves into code. Along the way you will trace my accepted solution line by line, derive a shorter version, and prove that it is correct.
Every section follows the same rhythm: an explanation, a concrete example, something to look at or interact with, a common misconception, and a short question to check yourself. Open the question only after you have an answer in mind.
1. What the problem asks
You are given a list of integers called nums. Move every 0 to the end of the list. The non-zero values must stay in the same order they had at the start.
Input: [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]Read the output from left to right: 1, then 3, then 12. That is exactly the order in which they appear in the input. The two zeroes have moved behind them.
The list changes; the function returns None
LeetCode does not want a new list back. The method signature ends in -> None: the method changes the list it was given and returns nothing. Two separate things exist after the call: the final arrangement of the list, and the return value of the function.
nums = [0, 1, 0, 3, 12]
result = Solution().moveZeroes(nums)
print(nums) # [1, 3, 12, 0, 0] ← the list was rearranged
print(result) # None ← nothing was returnedCommon misconception“The answer is what the function returns.” Here the answer is the state of
numsafter the call. Addingreturn numsdoes not help: LeetCode inspects the list you were given.
Check yourself: what does print(Solution().moveZeroes([0, 5])) print?
None. The list is rearranged to [5, 0] inside the call, but the method returns nothing, so print receives None.
What “in place” means
In place means you rearrange the values inside the same list object, using only a small, fixed number of extra variables. You do not build a second list and copy it back.
Picture five numbered boxes on a shelf. You may swap the contents of two boxes, or overwrite a box. You may not fetch a second shelf.
def moveZeroes(self, nums):
nums = [x for x in nums if x != 0] + [0] * nums.count(0)
# The caller's list is unchanged: this only rebinds the local name.Common misconception“Assigning to nums inside the function changes the caller’s list.”
nums = ...makes the local name point to a brand-new list. The caller still holds the original, untouched list. Writingnums[:] = ...would change the original, but it still builds a temporary list of size n first, so it is not using O(1) extra space.
Check yourself: is swapping nums[0] and nums[3] an in-place operation?
Yes. It reads and writes two cells of the same list and needs at most one temporary variable, however long the list is.
Why the order of non-zero values matters
The rule is not only “zeroes at the end”. The non-zero values must keep their relative order: whichever came first in the input must still come first in the output.
Example: for [0, 3, 1] the only correct answer is [3, 1, 0]. [1, 3, 0] also has the zero at the end, but 1 and 3 have swapped places, so it is wrong.
Common misconception“Any arrangement with the zeroes at the end is accepted.” Order is part of the requirement. It is also what makes the problem interesting: without it, you could swap freely.
Check yourself: which of [2, -1, 0, 0] and [-1, 2, 0, 0] is correct for [2, 0, -1, 0]?
[2, -1, 0, 0]. In the input, 2 appears before −1, so it must stay before −1.
Why sorting is not the answer
Sorting arranges values by size. That is a different goal. sorted([0, 1, 0, 3, 12]) gives [0, 0, 1, 3, 12], with the zeroes at the front. Sorting in reverse puts the zeroes last but reorders the rest: [0, 1, 3] becomes [3, 1, 0] instead of [1, 3, 0]. Negative numbers make it worse: they sort after zero in reverse order.
There is one sort that does work: nums.sort(key=lambda x: x == 0). Python’s sort is stable, so values with the same key keep their order. It is still the wrong tool for learning this problem: it costs O(n log n) time instead of O(n) and the sort can use extra temporary memory.
Common misconception“Zeroes are the smallest values, so sorting moves them.” Sorting moves them to the front, not the end, and it reorders every other value by size.
Check yourself: what does nums.sort(reverse=True) do to [-1, 0, 2]?
It produces [2, 0, -1]: the zero is not at the end and −1 has moved behind 2. The correct answer is [-1, 2, 0].
2. Forget the algorithm — what would you do by hand?
Before any code, solve it yourself. Select a cell, decide whether it is zero or non-zero, then pick a second cell to swap it with. Undo freely. The status line tells you whether the non-zero order is still intact. Each level unlocks the next.
Interactive exercise: with JavaScript enabled, swap cells by hand to move the zeroes in [0, 1, 0, 3, 12] without changing the order of 1, 3 and 12.
While you play, notice your own habits. Most people end up doing the same two things over and over: looking along the list for the next non-zero value, and putting it into the leftmost cell that does not yet hold a finished value.
Common misconception“I should chase the zeroes and push each one to the very end.” Pushing a zero to the end usually means swapping it past several non-zeroes, which breaks their order unless you shift everything one step at a time.
Check yourself: in [0, 1, 0, 3, 12], why is swapping 12 into index 0 a bad first move?
12 would end up before 1 and 3, but it comes after them in the input. The first value to place is the first non-zero you meet when reading from the left: the 1.
3. From your moves to a method
Recognising the repeated operation
Write down your moves for [0, 1, 0, 3, 12]. A natural sequence is: swap the 1 into index 0, swap the 3 into index 1, swap the 12 into index 2. Every move has the same shape: take the next non-zero from the left and place it in the next free slot at the front.
[0, 1, 0, 3, 12] 1 → slot 0
[1, 0, 0, 3, 12] 3 → slot 1
[1, 3, 0, 0, 12] 12 → slot 2
[1, 3, 12, 0, 0] doneWhy two positions must be tracked
To repeat that move you need to remember two facts at all times: where you are reading (the next value to inspect), and where the next non-zero should go (the next free slot). These two places move at different speeds. The reading position advances on every value; the slot advances only when it receives a non-zero. Because they drift apart, one index cannot do both jobs.
Common misconception“One loop variable is enough.” A single index can read every value, but it cannot also remember where the next non-zero belongs once a zero has been passed.
Assigning responsibilities to pointers
j, the scanner: visits every index from left to right and asks “is this value non-zero?”
i, the destination: marks the next slot that should receive a non-zero. Everything to its left is finished.
A pointer here is an index into the list, nothing more. Giving each one a single responsibility in one sentence is the key design step; the code follows from those sentences.
Check yourself: in [5, 0, 7], where are i and j just before 7 is placed?
i = 1 (the slot after the finished 5) and j = 2 (the 7 being read). After the swap the list is [5, 7, 0] and i becomes 2.
4. My original accepted solution
What I can state directly: I wrote the code below, it was accepted on 18 November 2026, and my approach was a zero-finding and swapping strategy: find a zero, then swap a later non-zero value into it.
What is reconstructed: the branch-by-branch reasoning in the next sections is a reading of the code written for this article. It explains why each branch works; it is not a record of what I was thinking at each line.
class Solution:
def moveZeroes(self, nums: list[int]) -> None:
i=0
j=i+1
temp=0
while(i<j and j<=len(nums)-1):
if(nums[i]==0 and nums[j]!=0):
temp=nums[j]
nums[j]=nums[i]
nums[i] = temp
elif(nums[i]!=0):
i+=1
j+=1
else:
j+=1Accepted · 75 / 75 test cases passed · runtime 12 ms · memory 20.52 MB · 18 November 2026. These are the figures from that submission. Being accepted shows the code is correct on LeetCode’s tests; it does not make it the clearest or fastest version.
In this version i parks on the first zero it finds and j looks ahead for a non-zero to swap into it. Step through it below. The highlighted line is the line Python is executing; the condition panel shows each Boolean expression, including the ones Python never evaluates because of short-circuiting.
Run the code one line at a time
Input: [0, 1, 0, 3, 12]. Interactive playback requires JavaScript; both complete traces remain readable below.
My original solution: 32 steps, 15 comparisons, 3 swaps → [1, 3, 12, 0, 0]
| Step | Line | i / j | nums | What happens |
|---|---|---|---|---|
| 1 | 3 | 0 / — | [0, 1, 0, 3, 12] | i=0i starts at index 0. It will stop on the first zero it meets. |
| 2 | 4 | 0 / 1 | [0, 1, 0, 3, 12] | j=i+1j starts one position to the right of i, at index 1. |
| 3 | 5 | 0 / 1 | [0, 1, 0, 3, 12] | temp=0temp is a spare variable for the three-step swap. |
| 4 | 6 | 0 / 1 | [0, 1, 0, 3, 12] | while(i<j and j<=len(nums)-1)Both parts are True, so the loop body runs with i = 0 and j = 1. |
| 5 | 7 | 0 / 1 | [0, 1, 0, 3, 12] | if(nums[i]==0 and nums[j]!=0)nums[0] is a zero and nums[1] = 1 is not. Swap them. |
| 6 | 8 | 0 / 1 | [0, 1, 0, 3, 12] | temp=nums[j]Save 1 from index 1 before it is overwritten. |
| 7 | 9 | 0 / 1 | [0, 0, 0, 3, 12] | nums[j]=nums[i]Copy the zero into index 1. For a moment the value 1 exists only in temp. |
| 8 | 10 | 0 / 1 | [1, 0, 0, 3, 12] | nums[i] = tempWrite 1 into index 0. The swap is complete; neither pointer moves in this pass. The next pass sees a non-zero at i and moves both. |
| 9 | 6 | 0 / 1 | [1, 0, 0, 3, 12] | while(i<j and j<=len(nums)-1)Both parts are True, so the loop body runs with i = 0 and j = 1. |
| 10 | 11 | 0 / 1 | [1, 0, 0, 3, 12] | elif(nums[i]!=0)nums[0] = 1 is already a non-zero in its final place. Move both pointers right. |
| 11 | 12, 13 | 1 / 2 | [1, 0, 0, 3, 12] | i+=1; j+=1i moves to 1 and j moves to 2. |
| 12 | 6 | 1 / 2 | [1, 0, 0, 3, 12] | while(i<j and j<=len(nums)-1)Both parts are True, so the loop body runs with i = 1 and j = 2. |
| 13 | 14 | 1 / 2 | [1, 0, 0, 3, 12] | elsenums[1] and nums[2] are both zero. Keep i on the first zero and move j on. |
| 14 | 15 | 1 / 3 | [1, 0, 0, 3, 12] | j+=1j moves to 3; i stays at 1, the zero waiting to be filled. |
| 15 | 6 | 1 / 3 | [1, 0, 0, 3, 12] | while(i<j and j<=len(nums)-1)Both parts are True, so the loop body runs with i = 1 and j = 3. |
| 16 | 7 | 1 / 3 | [1, 0, 0, 3, 12] | if(nums[i]==0 and nums[j]!=0)nums[1] is a zero and nums[3] = 3 is not. Swap them. |
| 17 | 8 | 1 / 3 | [1, 0, 0, 3, 12] | temp=nums[j]Save 3 from index 3 before it is overwritten. |
| 18 | 9 | 1 / 3 | [1, 0, 0, 0, 12] | nums[j]=nums[i]Copy the zero into index 3. For a moment the value 3 exists only in temp. |
| 19 | 10 | 1 / 3 | [1, 3, 0, 0, 12] | nums[i] = tempWrite 3 into index 1. The swap is complete; neither pointer moves in this pass. The next pass sees a non-zero at i and moves both. |
| 20 | 6 | 1 / 3 | [1, 3, 0, 0, 12] | while(i<j and j<=len(nums)-1)Both parts are True, so the loop body runs with i = 1 and j = 3. |
| 21 | 11 | 1 / 3 | [1, 3, 0, 0, 12] | elif(nums[i]!=0)nums[1] = 3 is already a non-zero in its final place. Move both pointers right. |
| 22 | 12, 13 | 2 / 4 | [1, 3, 0, 0, 12] | i+=1; j+=1i moves to 2 and j moves to 4. |
| 23 | 6 | 2 / 4 | [1, 3, 0, 0, 12] | while(i<j and j<=len(nums)-1)Both parts are True, so the loop body runs with i = 2 and j = 4. |
| 24 | 7 | 2 / 4 | [1, 3, 0, 0, 12] | if(nums[i]==0 and nums[j]!=0)nums[2] is a zero and nums[4] = 12 is not. Swap them. |
| 25 | 8 | 2 / 4 | [1, 3, 0, 0, 12] | temp=nums[j]Save 12 from index 4 before it is overwritten. |
| 26 | 9 | 2 / 4 | [1, 3, 0, 0, 0] | nums[j]=nums[i]Copy the zero into index 4. For a moment the value 12 exists only in temp. |
| 27 | 10 | 2 / 4 | [1, 3, 12, 0, 0] | nums[i] = tempWrite 12 into index 2. The swap is complete; neither pointer moves in this pass. The next pass sees a non-zero at i and moves both. |
| 28 | 6 | 2 / 4 | [1, 3, 12, 0, 0] | while(i<j and j<=len(nums)-1)Both parts are True, so the loop body runs with i = 2 and j = 4. |
| 29 | 11 | 2 / 4 | [1, 3, 12, 0, 0] | elif(nums[i]!=0)nums[2] = 12 is already a non-zero in its final place. Move both pointers right. |
| 30 | 12, 13 | 3 / 5 | [1, 3, 12, 0, 0] | i+=1; j+=1i moves to 3 and j moves to 5. |
| 31 | 6 | 3 / 5 | [1, 3, 12, 0, 0] | while(i<j and j<=len(nums)-1)j = 5 is past the last index 4, so the loop stops. |
| 32 | 6 | 3 / 5 | [1, 3, 12, 0, 0] | return NoneDone. nums is now [1, 3, 12, 0, 0]. The method itself returns None. |
Simplified solution: 18 steps, 5 comparisons, 3 swaps → [1, 3, 12, 0, 0]
| Step | Line | i / j | nums | What happens |
|---|---|---|---|---|
| 1 | 3 | 0 / — | [0, 1, 0, 3, 12] | i = 0i marks the next position that should receive a non-zero value. |
| 2 | 5 | 0 / 0 | [0, 1, 0, 3, 12] | for j in range(len(nums))j visits index 0, value 0. |
| 3 | 6 | 0 / 0 | [0, 1, 0, 3, 12] | if nums[j] != 0nums[0] is zero. Skip it: i stays at 0, still waiting for the next non-zero value. |
| 4 | 5 | 0 / 1 | [0, 1, 0, 3, 12] | for j in range(len(nums))j visits index 1, value 1. |
| 5 | 6 | 0 / 1 | [0, 1, 0, 3, 12] | if nums[j] != 0nums[1] = 1 is non-zero, so it belongs at index 0. |
| 6 | 7 | 0 / 1 | [1, 0, 0, 3, 12] | nums[i], nums[j] = nums[j], nums[i]Swap index 0 and index 1: 1 moves left to its destination and the zero moves right. |
| 7 | 8 | 1 / 1 | [1, 0, 0, 3, 12] | i += 1The destination slot is filled, so i moves to 1. |
| 8 | 5 | 1 / 2 | [1, 0, 0, 3, 12] | for j in range(len(nums))j visits index 2, value 0. |
| 9 | 6 | 1 / 2 | [1, 0, 0, 3, 12] | if nums[j] != 0nums[2] is zero. Skip it: i stays at 1, still waiting for the next non-zero value. |
| 10 | 5 | 1 / 3 | [1, 0, 0, 3, 12] | for j in range(len(nums))j visits index 3, value 3. |
| 11 | 6 | 1 / 3 | [1, 0, 0, 3, 12] | if nums[j] != 0nums[3] = 3 is non-zero, so it belongs at index 1. |
| 12 | 7 | 1 / 3 | [1, 3, 0, 0, 12] | nums[i], nums[j] = nums[j], nums[i]Swap index 1 and index 3: 3 moves left to its destination and the zero moves right. |
| 13 | 8 | 2 / 3 | [1, 3, 0, 0, 12] | i += 1The destination slot is filled, so i moves to 2. |
| 14 | 5 | 2 / 4 | [1, 3, 0, 0, 12] | for j in range(len(nums))j visits index 4, value 12. |
| 15 | 6 | 2 / 4 | [1, 3, 0, 0, 12] | if nums[j] != 0nums[4] = 12 is non-zero, so it belongs at index 2. |
| 16 | 7 | 2 / 4 | [1, 3, 12, 0, 0] | nums[i], nums[j] = nums[j], nums[i]Swap index 2 and index 4: 12 moves left to its destination and the zero moves right. |
| 17 | 8 | 3 / 4 | [1, 3, 12, 0, 0] | i += 1The destination slot is filled, so i moves to 3. |
| 18 | 5 | 3 / 4 | [1, 3, 12, 0, 0] | return NoneDone. nums is now [1, 3, 12, 0, 0]. The method itself returns None. |
Check yourself: in the trace of [0, 1, 0, 3, 12], why does the list briefly contain two zeroes and no 1?
Line 9 copies the zero into nums[j] before line 10 writes the saved value back into nums[i]. Between those lines the 1 exists only in temp. That intermediate state is real, which is why the animation shows it.
5. Every condition, one at a time
Each pass of the while loop runs exactly one of three branches. Python checks them from top to bottom and stops at the first one that is True.
if nums[i] == 0 and nums[j] != 0 — swap
Meaning: i is sitting on a zero and j has found a non-zero. That is the situation the strategy is waiting for, so the two values are swapped with temp. Example: [1, 0, 0, 3] with i = 1, j = 3 becomes [1, 3, 0, 0].
and short-circuits: if nums[i] == 0 is False, Python never evaluates nums[j] != 0. The evaluator below marks that as “not evaluated”.
elif nums[i] != 0 — move both
Meaning: the value at i is already non-zero, so it is finished and i can move on. j moves too, to stay one step ahead. Example: [1, 0, 0, 3] with i = 0, j = 1: 1 is in its final place, so i becomes 1 and j becomes 2.
else — move j only
Reaching else means both earlier tests failed: nums[i] is zero (or the elif would have run) and nums[j] is zero too (or the if would have run). There is nothing to swap, so i stays on its zero and j looks further right. Example: [1, 0, 0, 3] with i = 1, j = 2 → j becomes 3.
Common misconception“else means nums[j] is zero.” It means two things at once: nums[i] is zero and nums[j] is zero. Reading an else branch always means negating every condition above it.
This interactive section requires JavaScript.
Why the pointers do not move after a swap
After a swap, nothing advances. On the next pass the value at i is non-zero (it was just placed there), so nums[i] == 0 is False and the elif moves both pointers. The swap and the advance happen in two separate passes. This works, but it costs an extra trip through the loop for every swap. Moving both pointers inside the swap branch would be a valid refactor, because the elif would make that same move next anyway.
Check yourself: if you deleted the elif branch, what would happen on [1, 0]?
i = 0 holds 1, so the if fails and the program falls into else: j becomes 2, the loop ends, and i never moved. Here the result is still correct by luck. On [1, 0, 2] it fails: j skips past the 2 without swapping it, because i is parked on a non-zero, so the list stays [1, 0, 2].
6. The mental shift: place non-zeroes, ignore zeroes
Instead of moving zeroes to the end, place non-zero elements at the beginning. If every non-zero ends up at the front in its original order, the zeroes have nowhere else to be: they fill the remaining cells automatically.
This is the move you discovered by hand in section 3. The scanner j visits each index. The destination i waits for the next non-zero. When j finds one, it goes to slot i and i moves one step right. When j finds a zero, nothing happens: the zero will be pushed right later by a swap.
j = 0: 0 → skip [0, 1, 0, 3, 12] i = 0
j = 1: 1 → swap with slot 0 [1, 0, 0, 3, 12] i = 1
j = 2: 0 → skip [1, 0, 0, 3, 12] i = 1
j = 3: 3 → swap with slot 1 [1, 3, 0, 0, 12] i = 2
j = 4: 12 → swap with slot 2 [1, 3, 12, 0, 0] i = 3Turning those two responsibilities into Python gives:
class Solution:
def moveZeroes(self, nums: list[int]) -> None:
i = 0
for j in range(len(nums)):
if nums[j] != 0:
nums[i], nums[j] = nums[j], nums[i]
i += 1Line by line
i = 0: the first slot to fill is index 0.for j in range(len(nums)): j takes every index 0, 1, …, n − 1, once each. For an empty list the loop body never runs.if nums[j] != 0: the scanner decides. Zeroes fail the test and are skipped.nums[i], nums[j] = nums[j], nums[i]: tuple assignment. Python first evaluates the right-hand side into a pair of values, then assigns them to the left-hand targets. Both old values are read before anything is overwritten, so no temp variable is needed.i += 1: inside the if. The destination moves only after it has been filled with a non-zero.
Self-swaps. Until the first zero appears, i and j are equal, so the line swaps a cell with itself. For [1, 2, 0, 3], j = 0 and j = 1 are self-swaps. They leave the value unchanged and are harmless. Adding if i != j would skip them at the cost of one extra comparison per non-zero.
Common misconception“i should advance on every iteration, like j.” If i moved for zeroes too, it would skip over the zero slots that non-zeroes need to fill. Exercise 7 in section 10 shows the exact bug.
Run the code one line at a time
Input: [0, 1, 0, 3, 12]. Interactive playback requires JavaScript; both complete traces remain readable below.
My original solution: 32 steps, 15 comparisons, 3 swaps → [1, 3, 12, 0, 0]
| Step | Line | i / j | nums | What happens |
|---|---|---|---|---|
| 1 | 3 | 0 / — | [0, 1, 0, 3, 12] | i=0i starts at index 0. It will stop on the first zero it meets. |
| 2 | 4 | 0 / 1 | [0, 1, 0, 3, 12] | j=i+1j starts one position to the right of i, at index 1. |
| 3 | 5 | 0 / 1 | [0, 1, 0, 3, 12] | temp=0temp is a spare variable for the three-step swap. |
| 4 | 6 | 0 / 1 | [0, 1, 0, 3, 12] | while(i<j and j<=len(nums)-1)Both parts are True, so the loop body runs with i = 0 and j = 1. |
| 5 | 7 | 0 / 1 | [0, 1, 0, 3, 12] | if(nums[i]==0 and nums[j]!=0)nums[0] is a zero and nums[1] = 1 is not. Swap them. |
| 6 | 8 | 0 / 1 | [0, 1, 0, 3, 12] | temp=nums[j]Save 1 from index 1 before it is overwritten. |
| 7 | 9 | 0 / 1 | [0, 0, 0, 3, 12] | nums[j]=nums[i]Copy the zero into index 1. For a moment the value 1 exists only in temp. |
| 8 | 10 | 0 / 1 | [1, 0, 0, 3, 12] | nums[i] = tempWrite 1 into index 0. The swap is complete; neither pointer moves in this pass. The next pass sees a non-zero at i and moves both. |
| 9 | 6 | 0 / 1 | [1, 0, 0, 3, 12] | while(i<j and j<=len(nums)-1)Both parts are True, so the loop body runs with i = 0 and j = 1. |
| 10 | 11 | 0 / 1 | [1, 0, 0, 3, 12] | elif(nums[i]!=0)nums[0] = 1 is already a non-zero in its final place. Move both pointers right. |
| 11 | 12, 13 | 1 / 2 | [1, 0, 0, 3, 12] | i+=1; j+=1i moves to 1 and j moves to 2. |
| 12 | 6 | 1 / 2 | [1, 0, 0, 3, 12] | while(i<j and j<=len(nums)-1)Both parts are True, so the loop body runs with i = 1 and j = 2. |
| 13 | 14 | 1 / 2 | [1, 0, 0, 3, 12] | elsenums[1] and nums[2] are both zero. Keep i on the first zero and move j on. |
| 14 | 15 | 1 / 3 | [1, 0, 0, 3, 12] | j+=1j moves to 3; i stays at 1, the zero waiting to be filled. |
| 15 | 6 | 1 / 3 | [1, 0, 0, 3, 12] | while(i<j and j<=len(nums)-1)Both parts are True, so the loop body runs with i = 1 and j = 3. |
| 16 | 7 | 1 / 3 | [1, 0, 0, 3, 12] | if(nums[i]==0 and nums[j]!=0)nums[1] is a zero and nums[3] = 3 is not. Swap them. |
| 17 | 8 | 1 / 3 | [1, 0, 0, 3, 12] | temp=nums[j]Save 3 from index 3 before it is overwritten. |
| 18 | 9 | 1 / 3 | [1, 0, 0, 0, 12] | nums[j]=nums[i]Copy the zero into index 3. For a moment the value 3 exists only in temp. |
| 19 | 10 | 1 / 3 | [1, 3, 0, 0, 12] | nums[i] = tempWrite 3 into index 1. The swap is complete; neither pointer moves in this pass. The next pass sees a non-zero at i and moves both. |
| 20 | 6 | 1 / 3 | [1, 3, 0, 0, 12] | while(i<j and j<=len(nums)-1)Both parts are True, so the loop body runs with i = 1 and j = 3. |
| 21 | 11 | 1 / 3 | [1, 3, 0, 0, 12] | elif(nums[i]!=0)nums[1] = 3 is already a non-zero in its final place. Move both pointers right. |
| 22 | 12, 13 | 2 / 4 | [1, 3, 0, 0, 12] | i+=1; j+=1i moves to 2 and j moves to 4. |
| 23 | 6 | 2 / 4 | [1, 3, 0, 0, 12] | while(i<j and j<=len(nums)-1)Both parts are True, so the loop body runs with i = 2 and j = 4. |
| 24 | 7 | 2 / 4 | [1, 3, 0, 0, 12] | if(nums[i]==0 and nums[j]!=0)nums[2] is a zero and nums[4] = 12 is not. Swap them. |
| 25 | 8 | 2 / 4 | [1, 3, 0, 0, 12] | temp=nums[j]Save 12 from index 4 before it is overwritten. |
| 26 | 9 | 2 / 4 | [1, 3, 0, 0, 0] | nums[j]=nums[i]Copy the zero into index 4. For a moment the value 12 exists only in temp. |
| 27 | 10 | 2 / 4 | [1, 3, 12, 0, 0] | nums[i] = tempWrite 12 into index 2. The swap is complete; neither pointer moves in this pass. The next pass sees a non-zero at i and moves both. |
| 28 | 6 | 2 / 4 | [1, 3, 12, 0, 0] | while(i<j and j<=len(nums)-1)Both parts are True, so the loop body runs with i = 2 and j = 4. |
| 29 | 11 | 2 / 4 | [1, 3, 12, 0, 0] | elif(nums[i]!=0)nums[2] = 12 is already a non-zero in its final place. Move both pointers right. |
| 30 | 12, 13 | 3 / 5 | [1, 3, 12, 0, 0] | i+=1; j+=1i moves to 3 and j moves to 5. |
| 31 | 6 | 3 / 5 | [1, 3, 12, 0, 0] | while(i<j and j<=len(nums)-1)j = 5 is past the last index 4, so the loop stops. |
| 32 | 6 | 3 / 5 | [1, 3, 12, 0, 0] | return NoneDone. nums is now [1, 3, 12, 0, 0]. The method itself returns None. |
Simplified solution: 18 steps, 5 comparisons, 3 swaps → [1, 3, 12, 0, 0]
| Step | Line | i / j | nums | What happens |
|---|---|---|---|---|
| 1 | 3 | 0 / — | [0, 1, 0, 3, 12] | i = 0i marks the next position that should receive a non-zero value. |
| 2 | 5 | 0 / 0 | [0, 1, 0, 3, 12] | for j in range(len(nums))j visits index 0, value 0. |
| 3 | 6 | 0 / 0 | [0, 1, 0, 3, 12] | if nums[j] != 0nums[0] is zero. Skip it: i stays at 0, still waiting for the next non-zero value. |
| 4 | 5 | 0 / 1 | [0, 1, 0, 3, 12] | for j in range(len(nums))j visits index 1, value 1. |
| 5 | 6 | 0 / 1 | [0, 1, 0, 3, 12] | if nums[j] != 0nums[1] = 1 is non-zero, so it belongs at index 0. |
| 6 | 7 | 0 / 1 | [1, 0, 0, 3, 12] | nums[i], nums[j] = nums[j], nums[i]Swap index 0 and index 1: 1 moves left to its destination and the zero moves right. |
| 7 | 8 | 1 / 1 | [1, 0, 0, 3, 12] | i += 1The destination slot is filled, so i moves to 1. |
| 8 | 5 | 1 / 2 | [1, 0, 0, 3, 12] | for j in range(len(nums))j visits index 2, value 0. |
| 9 | 6 | 1 / 2 | [1, 0, 0, 3, 12] | if nums[j] != 0nums[2] is zero. Skip it: i stays at 1, still waiting for the next non-zero value. |
| 10 | 5 | 1 / 3 | [1, 0, 0, 3, 12] | for j in range(len(nums))j visits index 3, value 3. |
| 11 | 6 | 1 / 3 | [1, 0, 0, 3, 12] | if nums[j] != 0nums[3] = 3 is non-zero, so it belongs at index 1. |
| 12 | 7 | 1 / 3 | [1, 3, 0, 0, 12] | nums[i], nums[j] = nums[j], nums[i]Swap index 1 and index 3: 3 moves left to its destination and the zero moves right. |
| 13 | 8 | 2 / 3 | [1, 3, 0, 0, 12] | i += 1The destination slot is filled, so i moves to 2. |
| 14 | 5 | 2 / 4 | [1, 3, 0, 0, 12] | for j in range(len(nums))j visits index 4, value 12. |
| 15 | 6 | 2 / 4 | [1, 3, 0, 0, 12] | if nums[j] != 0nums[4] = 12 is non-zero, so it belongs at index 2. |
| 16 | 7 | 2 / 4 | [1, 3, 12, 0, 0] | nums[i], nums[j] = nums[j], nums[i]Swap index 2 and index 4: 12 moves left to its destination and the zero moves right. |
| 17 | 8 | 3 / 4 | [1, 3, 12, 0, 0] | i += 1The destination slot is filled, so i moves to 3. |
| 18 | 5 | 3 / 4 | [1, 3, 12, 0, 0] | return NoneDone. nums is now [1, 3, 12, 0, 0]. The method itself returns None. |
Check yourself: what is the value of i when the loop finishes on [0, 1, 0, 3, 12]?
3: one step for each non-zero placed. In general, i ends equal to the number of non-zero values.
7. Why it works: the loop invariant
Running a few examples shows that the code works on those examples. An invariant explains why it works on every input. An invariant is a statement about the program’s state that is true before every iteration of a loop.
The invariantBefore each iteration, the first
ipositions contain all non-zero elements encountered so far, in their original relative order.
It is proved in three stages.
Initialisation: before the first iteration, i = 0 and j = 0. Nothing has been encountered and the first 0 positions are empty, so the statement is true.
Maintenance: assume it is true before the iteration for some j. If nums[j] is zero, nothing changes, and no new non-zero was encountered, so it stays true. If nums[j] is non-zero, it is swapped into position i, directly after the earlier non-zeroes, and i grows by one. It is the newest non-zero encountered, and it is now last in the prefix, so the order is still correct.
Termination: the loop ends when j has visited every index. Every non-zero has been encountered, so the first i positions hold all of them, in order. The remaining positions hold the values that were swapped out of the prefix region, and those are all zeroes.
Together, the three stages cover any length and any values. That is the difference between a proof and a set of passing examples: the argument never depends on which particular numbers are in the list.
Watch the invariant hold
- initialisation, j = 0, i = 0: first i positions
[]; non-zeroes seen[] - maintenance, j = 1, i = 0: first i positions
[]; non-zeroes seen[] - maintenance, j = 2, i = 1: first i positions
[1]; non-zeroes seen[1] - maintenance, j = 3, i = 1: first i positions
[1]; non-zeroes seen[1] - maintenance, j = 4, i = 2: first i positions
[1, 3]; non-zeroes seen[1, 3] - termination, j = 5, i = 3: first i positions
[1, 3, 12]; non-zeroes seen[1, 3, 12]
Common misconception“The invariant must hold after every single line.” It only has to hold at the boundary between iterations. Midway through an iteration, after the swap but before i += 1, it is briefly not true, and that is fine.
Check yourself: in the original solution, what plays the role of the shaded region?
The positions before i. Every value there is a finished non-zero in its original order. Whenever nums[i] is zero, the positions from i up to j − 1 are all zeroes, waiting to be filled.
8. Edge-case laboratory
Run both implementations on the cases most likely to break an index: empty input, one element, no zeroes, only zeroes, and a non-zero at the very end. Expected outputs are computed independently of either implementation.
Edge-case laboratory
| Input | Expected | Original | Simplified |
|---|---|---|---|
[] | [] | [] | [] |
[0] | [0] | [0] | [0] |
[1] | [1] | [1] | [1] |
[0, 0, 0] | [0, 0, 0] | [0, 0, 0] | [0, 0, 0] |
[1, 2, 3] | [1, 2, 3] | [1, 2, 3] | [1, 2, 3] |
[0, 0, 1] | [1, 0, 0] | [1, 0, 0] | [1, 0, 0] |
[1, 0, 2, 0, 3] | [1, 2, 3, 0, 0] | [1, 2, 3, 0, 0] | [1, 2, 3, 0, 0] |
[0, 1, 0, 1, 0, 1] | [1, 1, 1, 0, 0, 0] | [1, 1, 1, 0, 0, 0] | [1, 1, 1, 0, 0, 0] |
[-1, 0, -2, 0, 3] | [-1, -2, 3, 0, 0] | [-1, -2, 3, 0, 0] | [-1, -2, 3, 0, 0] |
[0, 1, 0, 3, 12] | [1, 3, 12, 0, 0] | [1, 3, 12, 0, 0] | [1, 3, 12, 0, 0] |
Two details are worth checking by hand. For [], [0] and [1], the original solution never enters its loop: j starts at 1, which is already past the last index. The simplified solution handles them without special cases, because range(0) is empty and a single non-zero is a self-swap.
Check yourself: for [1, 2, 3], how many swaps does each version perform?
The original performs none: every pass takes the elif branch. The simplified version performs three, all self-swaps.
9. Complexity, visually
Simplified: the for loop runs exactly n times, with one comparison each time and at most one swap. That is O(n) time.
Original: j starts at 1 and ends at n, so it moves at most n − 1 times. A pass that swaps does not move j, but the very next pass always takes the elif branch and moves j. So there are at most 2(n − 1) passes, each with at most three comparisons: also O(n).
Space: both versions keep a fixed number of extra variables (i, j and, in the original, temp), whatever the length of the list. That is O(1) extra space.
This interactive section requires JavaScript.
Big-O is not a stopwatch. O(n) describes how the work grows as n grows. LeetCode’s runtime, and the percentile beside it, is one measurement on a shared machine: it changes between submissions of identical code. The 12 ms on my submission says the code was fast enough on those tests, not that it beats another O(n) version.
Fewer branches is not automatically faster. The simplified version has one condition instead of three, but it performs self-swaps that the original avoids. On [1, 2, 3] it performs three self-swaps while the original performs no swaps at all. Which runs faster in practice depends on the input and the interpreter; both are O(n).
Check yourself: if n doubles, roughly what happens to the simplified version’s number of comparisons?
It doubles exactly: one comparison per element.
10. Check your understanding
Eight short exercises, from prediction to explanation. Each wrong answer explains the misunderstanding behind it. You can reveal a full explanation at any time; doing so also unlocks the next exercise.
This interactive section requires JavaScript.
11. Comparing both approaches fairly
My original solution | Simplified solution | |
|---|---|---|
Mental model | Find a zero, then swap a later non-zero into it | Place each non-zero at the next free slot; ignore zeroes |
Pointer responsibilities | i parks on the first zero; j searches ahead | j scans every index; i marks the next destination |
Branching | while with two conditions; if / elif / else | for loop; one if |
Number of swaps | Only real swaps (zero ↔ non-zero) | The same real swaps, plus self-swaps before the first zero |
Readability | Needs care: each branch depends on the others | Each line maps to one responsibility |
Correctness | Correct (accepted; also verified exhaustively for this article) | Correct (proved by the invariant) |
Time complexity | O(n): at most 2(n − 1) passes | O(n): exactly n passes |
Space complexity | O(1) extra | O(1) extra |
Neither version is asymptotically better: both are O(n) time and O(1) extra space. The simplified version is easier to reason about, and that is the main reason to prefer it. The original reached the right answer through a different, valid mental model.
How I Would Discover This Algorithm Again
The steps that led here are not specific to zeroes. This is the sequence I would follow on the next in-place array problem:
Understand the required output, including what is returned.
Identify what must remain unchanged (here, the order of non-zeroes).
Simulate manually on small inputs.
Identify the repeated operation in your own moves.
Determine what information you had to remember.
Assign one responsibility to each pointer, in one sentence each.
Write an invariant that those responsibilities keep true.
Implement directly from the responsibilities.
Test the edge cases: empty, one element, none and all of the special value.
Simplify, and re-check the invariant after simplifying.
A reusable checklist for in-place array problems:
Can I state the exact final arrangement, and what the function returns?
What must keep its relative order?
Which index reads, and which index writes?
When exactly does the write index move?
What is true about the prefix before every iteration?
Does my loop handle [], one element, and no special values?
Is my extra space independent of n?
Remove Duplicates from Sorted Array and Remove Element use the same reader/writer structure with a different test in the if. Try them with this checklist before looking anything up.
Problem and accepted submission
- Platform
- LeetCode
- Problem number
- 283
- Problem difficulty
- Easy
- Pattern
- Two Pointers — Reader and Writer
- Solution language
- Python 3
Accepted · 75 / 75 test cases · 12 ms · 20.52 MB · 18 November 2026. These are the supplied submission figures for my original solution, not measurements of the animations or a benchmark.
Revisit Reverse String for the first in-place two-pointer swap in this series, or 3Sum Closest for pointers that close in from both ends.