Lesson guide
What this Python exercise practices
Move Zeros In-Place with Two Pointers is a beginner practice lesson that focuses on dsa, problem patterns, edge cases. It is designed to be solved in about 10 minutes with examples, starter code, and test feedback.
Prerequisites
- Python functions
- Loops
- Lists
- Basic edge cases
Difficulty and time
- Level
- Beginner
- Estimated time
- 10 minutes
Related public exercises
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.
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.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.