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.
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
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:
- 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.
- If left is not pointing to a zero: simply advance left
- 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.