Move Zeroes - Problem

Given an integer array nums, you need to move all zeros to the end while keeping the relative order of non-zero elements intact. This is like organizing a bookshelf where you want to push all the empty spaces to one end!

The challenge is that you must do this in-place without creating a new array. Think of it as rearranging items on a conveyor belt without stopping the belt.

Example: [0,1,0,3,12] becomes [1,3,12,0,0]

Goal: Transform the array so all zeros are at the end, non-zero elements maintain their original relative positions, and you use O(1) extra space.

Input & Output

example_1.py โ€” Basic Case
$ Input: [0,1,0,3,12]
โ€บ Output: [1,3,12,0,0]
๐Ÿ’ก Note: Move all zeros to the end while maintaining the relative order of non-zero elements. The non-zero elements 1, 3, 12 keep their relative positions, and zeros are moved to the end.
example_2.py โ€” Single Zero
$ Input: [0]
โ€บ Output: [0]
๐Ÿ’ก Note: Array with single zero remains unchanged as there are no non-zero elements to rearrange.
example_3.py โ€” No Zeros
$ Input: [1,2,3,4,5]
โ€บ Output: [1,2,3,4,5]
๐Ÿ’ก Note: Array with no zeros remains unchanged as there are no zeros to move. All elements maintain their original positions.

Constraints

  • 1 โ‰ค nums.length โ‰ค 104
  • -231 โ‰ค nums[i] โ‰ค 231 - 1
  • Follow up: Could you minimize the total number of operations done?

Visualization

Tap to expand
Library Shelf OrganizationBefore: Mixed Books and Empty SpotsEmpty๐Ÿ“šEmpty๐Ÿ“–๐Ÿ“˜Reorganize with Two PointersAfter: All Books Left, Empty Spots Right๐Ÿ“š๐Ÿ“–๐Ÿ“˜EmptyEmptyTwo Pointer Strategy๐Ÿ“– Read Pointer: Scans every position on shelfโœ๏ธ Write Pointer: Tracks where next book should goโšก Efficiency: Each book moved exactly once - O(n) time!Just like a librarian efficiently organizing books without wasting time!
Understanding the Visualization
1
Identify Books and Gaps
Scan the shelf to find books (non-zeros) and empty spots (zeros)
2
Move Books Left
Slide each book to the leftmost available position
3
Fill Right with Gaps
All empty spots naturally end up on the right side
4
Maintain Order
Books keep their relative positions throughout the process
Key Takeaway
๐ŸŽฏ Key Insight: Instead of moving zeros (expensive), focus on moving non-zeros to their correct positions - zeros naturally end up at the end!
Asked in
Facebook 45 Amazon 38 Microsoft 32 Google 28
89.3K Views
High Frequency
~15 min Avg. Time
2.8K 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