The Move Zeroes problem is a classic array manipulation question where the goal is to rearrange elements efficiently while preserving order.
๐ Problem Statement
Given an array nums, move all 0s to the end while maintaining the relative order of non-zero elements.
The operation must be done in-place without using extra space.
๐ Examples
Example 1:
Input: [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Example 2:
Input: [0]
Output: [0]
๐ง Intuition
We need to:
- Keep all non-zero elements in the same order
- Move all zeros to the end
๐ This can be done efficiently using a two-pointer approach
๐ Approach (Optimal Two-Pointer Method)
Step-by-Step:
Initialize a pointer
j = 0
(this will track position for next non-zero element)Traverse the array:
-
If
nums[i] != 0:- Swap
nums[i]withnums[j] - Increment
j
- Swap
๐ป Python Code
def move_zeroes(nums):
j = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[i], nums[j] = nums[j], nums[i]
j += 1
return nums
print(move_zeroes([0, 1, 0, 3, 12]))
๐งพ Dry Run
For: nums = [0, 1, 0, 3, 12]
Step-by-step:
- i = 0 โ 0 โ skip
- i = 1 โ 1 โ swap with index 0 โ [1, 0, 0, 3, 12]
- i = 2 โ 0 โ skip
- i = 3 โ 3 โ swap with index 1 โ [1, 3, 0, 0, 12]
- i = 4 โ 12 โ swap with index 2 โ [1, 3, 12, 0, 0]
Final Output: [1, 3, 12, 0, 0]
โก Complexity
Time Complexity: O(n)
Space Complexity: O(1)
๐ฅ Why This Works
- Maintains order of non-zero elements
- Minimizes unnecessary swaps
- Uses constant extra space
โ ๏ธ Follow-Up Optimization
To minimize operations:
๐ Only swap when i != j
This avoids swapping an element with itself.
๐ Conclusion
Move Zeroes is a simple yet powerful problem that teaches:
- Two-pointer technique
- In-place array manipulation
- Efficient traversal
Mastering this helps in many real-world and interview scenarios.
Top comments (0)