Hide sidebar

Move Zeroes

Move Zeroes

Two Pointers
EasyLeetCode #283
15 min

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. Note that you must do this in-place without making a copy of the array.

Example

Example 1:

Input: nums = [0,1,0,3,12]

nums: [0, 1, 0, 3, 12]

Output: [1, 3, 12, 0, 0]

Output: [1,3,12,0,0]

Solution

The two-pointer approach is efficient for this problem. We use one pointer (`l`) to keep track of the position of the next non-zero element, and another pointer (`r`) to iterate through the array. When `nums[r]` is non-zero, we swap it with `nums[l]` and increment `l`.

Algorithm Steps

  • Initialize a left pointer `l` to 0.
  • Iterate through the array with a right pointer `r`.
  • If `nums[r]` is not zero, swap `nums[l]` and `nums[r]`, then increment `l`.

Move Zeroes

Two Pointers Approach

Input: nums = [0, 1, 0, 3, 12]

Output: [0, 1, 0, 3, 12]

Progress1 / 1

Ready to start the visualization

Nums

0
1
0
3
12
Move Zeroes Solution

class Solution:
    def moveZeroes(self, nums: list[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        l = 0
        for r in range(len(nums)):
            if nums[r]:
                nums[l], nums[r] = nums[r], nums[l]
                l += 1