easy +10 pts

Move Zeros to End

Rearrange a list so all zeros are at the end while keeping the order of non-zero elements.

Write a function `move_zeros_to_end(nums: list[int]) -> list[int]` that takes a list of integers and returns a new list with all zeros moved to the end, while keeping the relative order of non-zero elements unchanged. The function should not use built-in sorting functions (like `sort` or `sorted`) and must not modify the original list.

Constraints

- The input list may contain any integers (positive, negative, zero). - The length of the list is between 0 and 10^5. - The function must run in O(n) time and use O(n) extra space (since a new list is returned).

Example

>>> move_zeros_to_end([0, 1, 0, 3, 12])
[1, 3, 12, 0, 0]
>>> move_zeros_to_end([0])
[0]
>>> move_zeros_to_end([-1, 0, 0, 2])
[-1, 2, 0, 0]
>>> move_zeros_to_end([])
[]
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think about using a two-pointer approach: one pointer for the position where the next non-zero should go, and another to scan the list.
Alternatively, you can build a new list by first appending all non-zero elements and then appending the necessary zeros.
Remember to preserve the relative order of non-zero elements.
Count zeros and use list concatenation or append operations for a clear solution.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.