Introduction
LeetCode 283: Move Zeroes asks you to reorder elements in an array by moving all zeros to the end while maintaining the relative order of the non-zero elements.
This is one of the best array manipulation and two-pointer problems you’ll encounter in interviews — clean, efficient, and elegant.
Problem Statement
Given an integer array nums
, move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
- Do this in-place without making a copy of the array.
- Minimize the total number of operations.
Example
python
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
✅ Step-by-Step Solution
🧠 Intuition
We can use a two-pointer approach:
- One pointer (
insert_pos
) keeps track of where the next non-zero element should go.
- The other pointer (
i
) scans the array.
🔄 Step-by-Step Process
- Initialize
insert_pos = 0
- Loop through the array:
- If
nums[i] != 0
:
- Place
nums[i]
at nums[insert_pos]
- Increment
insert_pos
- After loop ends, fill the rest of the array from
insert_pos
to end with 0
✅ Python Code
python
class Solution:
def moveZeroes(self, nums: list[int]) -> None:
insert_pos = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[insert_pos] = nums[i]
insert_pos += 1
for i in range(insert_pos, len(nums)):
nums[i] = 0
This modifies the array in-place without extra space.
🧪 Dry Run Example
Input: [0, 1, 0, 3, 12]
i=0
: 0 → skip
i=1
: 1 → place at insert_pos=0
, insert_pos=1
i=2
: 0 → skip
i=3
: 3 → place at insert_pos=1
, insert_pos=2
i=4
: 12 → place at insert_pos=2
, insert_pos=3
Fill rest with 0s:
→ [1, 3, 12, 0, 0]
⏱️ Time and Space Complexity
MetricValueTime ComplexityO(n)Space ComplexityO(1)In-Place✅ Yes
🛠️ Alternative: Swap-Based (Slightly Different Behavior)
python
class Solution:
def moveZeroes(self, nums: list[int]) -> None:
last_non_zero = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[i], nums[last_non_zero] = nums[last_non_zero], nums[i]
last_non_zero += 1
- This version swaps instead of assigning.
- Works well but may introduce more operations than necessary.
🔍 Edge Cases
[0, 0, 0]
→ stays [0, 0, 0]
[1, 2, 3]
→ no change
[]
→ empty list → no-op
✅ Conclusion
LeetCode 283: Move Zeroes is a fantastic warm-up for interview-style array problems. It teaches:
- Two-pointer strategies
- In-place transformation
- Optimal movement minimization