LeetCode 283. Move Zeroes

Post by ailswan Dec. 13, 2023

283. Move Zeroes

Problem Statement

link: LeetCode.cn LeetCode

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:

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

Input: nums = [0] Output: [0]

Solution Approach

The solution approach for this problem involves using a two-pointer approach to iterate through the array and move non-zero elements to the beginning, maintaining their relative order, and filling the remaining positions with zeros.

Algorithm

  1. Initialization: Set two pointers, i and j, both initially at 0.

  2. Non-Zero Element Movement: Iterate through the array with i. When a non-zero element is found, move it to the position indicated by j and increment both pointers.

  3. Fill with Zeros: After the first pass, continue with j to fill the remaining positions with zeros.

Implement

    class Solution:
      def moveZeroes(self, nums: List[int]) -> None:
          i = j = 0
          n = len(nums)
          while i < n:
              if nums[i] != 0:
                  nums[j] = nums[i]
                  j += 1
              i += 1
          while j < n:
              nums[j] = 0
              j += 1