💡
Exercise 14

Move Zeroes 15 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

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]:

  • read=0: nums[0]=0, skip. write stays at 0
  • read=1: nums[1]=1, write→ nums[0]=1, write=1
  • read=2: nums[2]=0, skip. write stays at 1
  • read=3: nums[3]=3, write→ nums[1]=3, write=2
  • read=4: nums[4]=12, write→ nums[2]=12, write=3
  • Fill rest: nums[3]=0, nums[4]=0
  • Result: [1, 3, 12, 0, 0] ✓

Complexity: Time O(n), Space O(1) — done in-place!

📋 Instructions
Implement `moveZeroes(nums)` that modifies the array **in-place**. - Move all 0s to the end - Keep relative order of non-zero elements - Do it in-place (don't create a new array) - Return the modified array
Start with write = 0. Loop through with 'for read in range(len(nums))'. If nums[read] != 0, set nums[write] = nums[read] and increment write. After the loop, fill positions from write to end with 0.
⚠️ Try solving it yourself first — you'll learn more!
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
🧪 Test Cases
Input
moveZeroes([0, 1, 0, 3, 12])
Expected
[1, 3, 12, 0, 0]
Test case 1
Input
moveZeroes([0])
Expected
[0]
Edge case — single element
Input
moveZeroes([1, 0, 0, 2, 3, 0])
Expected
[1, 2, 3, 0, 0, 0]
Test case 3
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.