What is Move Zeroes
Move every zero to the end and keep the order of the other values. Return the whole array. A write pointer marks the next slot for a non-zero. A read pointer scans the array once.
0 1 0 3 12 1 3 12 0 0
Approach
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | One pass of swaps. |
| Memory | O(1) | The same array is rearranged. |
Implementation
def move_zeroes(a):
w = 0
for r in range(len(a)):
if a[r] != 0:
a[w], a[r] = a[r], a[w]
w += 1
return a