Move All Zeros to the End

Medium ⏱ 12 min 64% acceptance ★★★★★ 4.9
Write move_zeros(items) that moves all 0 values in items to the end of the list while preserving the relative order of the non-zero elements. Modify and return the same list object (in place), using a two-pointer technique.

Examples

Example 1
Input
items = [0, 1, 0, 3, 12]
Output
[1, 3, 12, 0, 0]
Explanation

Non-zero elements keep their order; zeros are pushed to the end.

Constraints

  • 0 <= len(items) <= 10^5

Topics

ListsTwo Pointers

Companies

GoogleMicrosoft

Hints

Hint 1

Use a "write pointer" that tracks where the next non-zero value should go.

Hint 2

After placing all non-zero values, fill the remaining tail with zeros.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.