Move Zeroes - Problem
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Note: You must do this in-place without making a copy of the array.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [0,1,0,3,12]
›
Output:
[1,3,12,0,0]
💡 Note:
Move all zeros to the end while keeping non-zero elements in same relative order: 1, 3, 12 stay in order, zeros move to end
Example 2 — No Zeros
$
Input:
nums = [1,2,3]
›
Output:
[1,2,3]
💡 Note:
No zeros present, array remains unchanged
Example 3 — All Zeros
$
Input:
nums = [0,0,0]
›
Output:
[0,0,0]
💡 Note:
All elements are zeros, array remains the same
Constraints
- 1 ≤ nums.length ≤ 104
- -231 ≤ nums[i] ≤ 231 - 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array with zeros scattered throughout: [0,1,0,3,12]
2
Process
Move all non-zero elements to front, maintaining their order
3
Output
All zeros moved to end: [1,3,12,0,0]
Key Takeaway
🎯 Key Insight: Use two pointers - one tracks the position for the next non-zero element
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code