LeetCode #283: Move Zeroes — a great introduction to the two-pointer technique.
Given an array nums, move all 0s to the end while keeping the relative order of the other elements.
Example:[0, 1, 0, 3, 12] → [1, 3, 12, 0, 0]
The Trick — Two Pointers:
Use a write pointer to track where the next non-zero should go. Scan with a read pointer through the whole array.
💭 Now it's your turn! Using the approach above, implement your solution in the editor. You've got this! 💪
Walk-through with [0, 1, 0, 3, 12]:
Complexity: Time O(n), Space O(1) — done in-place!
def moveZeroes(nums):
write = 0 # Where to place next non-zero
for read in range(len(nums)): # Scan every element
if nums[read] != 0:
nums[write] = nums[read] # Place non-zero at write position
write += 1
# Fill the rest with zeroes
while write < len(nums):
nums[write] = 0
write += 1
moveZeroes([0, 1, 0, 3, 12])
[1, 3, 12, 0, 0]
moveZeroes([0])
[0]
moveZeroes([1, 0, 0, 2, 3, 0])
[1, 2, 3, 0, 0, 0]