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
Move Zeroes: Transform Array In-PlaceInput Array010312Move zeros to end, keep order of non-zerosOutput Array131200✅ Relative order preserved: 1 → 3 → 12✅ All zeros moved to end: 0, 0✅ In-place modification (no extra space)
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
Asked in
Facebook 25 Microsoft 20 Apple 15 Google 12
299.0K Views
High Frequency
~15 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen