Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Move Zeros Using Extra Space

Reorder an array so that all zeros appear at the end while keeping the relative order of the non-zero elements.

Python practice13 minArrays – Fundamentals & PatternsIntermediateLast updated March 25, 2026

Problem statement

Given an array nums, move all 0's to the end while maintaining the relative order of the non-zero elements. The function should return the new array (it may modify the input or create a new one). Aim for O(n) time and O(1) extra space (excluding output).

Task

Implement an in-place (or output-creating) algorithm that compacts non-zero elements to the front and appends zeros to the end in O(n) time and O(1) extra space.

Examples

Move zeros

Input

nums = [0, 1, 0, 3, 12]

Output

[1, 3, 12, 0, 0]

All non-zero elements keep their relative order and zeros are moved to the end.

Input format

Function input: move_zeros(nums) where nums is a list of integers.

Output format

Return a list of integers with zeros moved to the end and relative order preserved for non-zero elements.

Constraints

0 <= len(nums) <= 10^5. -10^9 <= nums[i] <= 10^9. Use O(n) time and O(1) extra space where possible.

Samples

Sample 1

Input

nums = [1, 2, 3]

Output

[1, 2, 3]

No zeros to move; output equals input.