Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Find a pair with target sum in a sorted arrayE02. Count unique values in a sorted arrayE03. Move Zeros In-Place with Two PointersE

Problem No 3

Move Zeros In-Place with Two Pointers

Easy

10 minute session

Summary

Reorder an array so that all zeros are moved to the end while preserving the order of non-zero elements.

Problem statement

Given a list of integers, move all zeros to the end of the list while maintaining the relative order of non-zero elements. Return the resulting list. Aim for O(n) time and O(1) extra space (in-place). The function should return the modified list.

Task

Return a list where all zeros are at the end and the relative order of non-zero elements is preserved, using an in-place two-pointer approach for O(n) time.

Examples

Example with zeros interleaved

Input

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

Output

[1, 3, 12, 0, 0]

Explanation

All non-zero elements appear in original order, and zeros are moved to the end.

Input format

A list of integers 'arr'. Function signature: move_zeros(arr).

Output format

Return the list after moving zeros to the end, preserving non-zero order.

Constraints

0 <= len(arr) <= 10^5. Use O(n) time and O(1) extra space if possible. You may return the same list object modified in-place.

Samples

Sample input 0

[1, 2, 3]

Sample output 0

[1, 2, 3]

Explanation 0

No zeros to move.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

07:06 PM

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.