Workspace Move Zeroes
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Move Zeroes visualizer

Move every zero to the end while preserving the order of nonzero entries. Return the rearranged copy.

EXECUTION LAB

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 a

Visualizer

Step 1 of 8
00i, write
13
20
3-2
45

Inspect the current state

Decide whether the value at 0 belongs at the write pointer 0.

Variable watch

i 0write 0

Step explanation

Decide whether the value at 0 belongs at the write pointer 0.

comparisons 1reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(n) time · O(n) returned copy, O(1) auxiliary space

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 1Passengers move forward to fill vacant seats without overtaking.
Hint 2Compact nonzero values into the front and fill the remaining positions with zero.
Hint 3Step 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?

Continue learning

Practice related DSA questions in the same topic.