[Problem] Move Zeroes

댕청·2025년 5월 17일

문제 풀이

목록 보기
2/38

https://leetcode.com/problems/move-zeroes

Since the main concepts I learned for the day are two-pointers and sliding windows, I solved a basic two pointer problem.

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.

Example

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

Solution

def moveZeroes(self, nums):
        #left: iterates through all of the points
        #right: keeps track of the non-zero digits

        left = 0
        right = len(nums) - 1
        while left < right:
            if nums[left] == 0 and nums[right] != 0:
                nums.append(nums.pop(left))
            elif nums[left] != 0:
                left += 1
            else: right -= 1
        
        return nums

The important part here is that we do not need to create an entirely new array to complete the task, but simply swap the elements accordingly then advance the zeros.

Therefore, I divided the situation into three cases:

  1. If left is pointing to a zero and right is pointing to an non-zero element: Then an element swap is required, where the zero is popped and appended to the end of the list.
  2. If left is not pointing to a zero: simply advance left
  3. For all other cases, since right is pointing to a zero, we can't be sure to progress left, so we only shift right.

While the problem itself is simple, having the minimum number of operations and minimizing space complexity is the key-point of the problem.

profile
될때까지 모든 걸 다시 한번

0개의 댓글