Continue learning
Practice related DSA questions in the same topic.
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.
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 aDecide whether the value at 0 belongs at the write pointer 0.
Decide whether the value at 0 belongs at the write pointer 0.
Passengers move forward to fill vacant seats without overtaking.
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
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} ⇒ []
A swap with the last element can reorder the nonzero values.
How could you avoid writing cells already in place?