easy +10 pts

Move Zeros to the End

Reorder a list in-place so all zeros are at the end while keeping the relative order of non-zero elements.

Write a function `move_zeros_to_end(nums)` that takes a list of integers `nums` and modifies it **in-place** so that all zeros are moved to the end of the list, preserving the relative order of the non-zero elements. The function should return the same list object (after modification). **Requirements:** - Modify the input list in-place. - Do not create a new list as the final result (you may use temporary variables). - The relative order of non-zero elements must be preserved. - All zero elements must be at the end. - The function should return the modified list.

Constraints

- The list may be empty or contain any number of integers (including negatives). - The list length is between 0 and 10^4. - Each element is an integer in the range [-10^4, 10^4]. - Time complexity: O(n) expected. - Space complexity: O(1) extra space (besides the input list).

Example

>>> nums = [0, 1, 0, 3, 12]
>>> result = move_zeros_to_end(nums)
>>> result is nums
True
>>> nums
[1, 3, 12, 0, 0]

>>> nums = [0, 0, 0]
>>> move_zeros_to_end(nums)
[0, 0, 0]
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use two pointers: one to iterate and one to track where the next non-zero should be placed.
First pass: move all non-zero elements to the front in order.
After moving non-zeros, fill the remaining positions with zeros.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.