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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code