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 - Optimal Solution INPUT Integer Array nums[] 0 [0] 1 [1] 0 [2] 3 [3] 12 [4] Zero elements Non-zero elements nums = [0, 1, 0, 3, 12] length = 5 Two-Pointer Technique ALGORITHM STEPS 1 Initialize Pointer Set writeIdx = 0 2 Iterate Array Loop through each element 3 Move Non-Zeros If nums[i] != 0, swap 4 Increment writeIdx After each non-zero swap Swap Operation 0 1 --> 1 0 swap(nums[writeIdx], nums[i]) Time: O(n) | Space: O(1) FINAL RESULT Modified Array (In-Place) 1 [0] 3 [1] 12 [2] 0 [3] 0 [4] Output: [1, 3, 12, 0, 0] In-place modification OK - Success Non-zeros: Relative order preserved (1, 3, 12) Zeros: Moved to end Key Insight: The two-pointer technique uses writeIdx to track where the next non-zero should go. When we find a non-zero element, we swap it with the position at writeIdx. This naturally pushes zeros to the end while maintaining the relative order of non-zero elements. No extra space needed - truly in-place! TutorialsPoint - Move Zeroes | Optimal Two-Pointer Approach
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