Move Zeroes
Move every zero to the end while preserving the order of nonzero entries. Return the rearranged copy.
Move every zero to the end while preserving the order of nonzero entries. Return the rearranged copy.
Input and constraints
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
def solve(values, target): a = values.copy() write = 0 i = 0 while (i < len(a)): if (a[i] != 0): a[write] = a[i] write = (write + 1) i = (i + 1) while (write < len(a)): a[write] = 0 write = (write + 1) return aVisualizer
Step 1 of 8Inspect the current state
Decide whether the value at 0 belongs at the write pointer 0.
Variable watch
Step explanation
Decide whether the value at 0 belongs at the write pointer 0.
Worked explanation
Passengers move forward to fill vacant seats without overtaking.
Guided solution
Compact nonzero values into the front and fill the remaining positions with zero.
O(n) time · O(n) returned copy, O(1) auxiliary auxiliary space
Examples
Worked example · {"values":[0,3,0,-2,5],"target":0} ⇒ [3,-2,5,0,0]
Edge case 1 · {"values":[0,0],"target":0} ⇒ [0,0]
Edge case 2 · {"values":[],"target":0} ⇒ []
Progressive hints
Hint 1
Passengers move forward to fill vacant seats without overtaking.Hint 2
Compact nonzero values into the front and fill the remaining positions with zero.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
A swap with the last element can reorder the nonzero values.
Interview follow-up
How could you avoid writing cells already in place?