LeetCode Problem 283: Move Zeroes
Given an integer array nums, move all 0s to the end of it while maintaining the relative order of the non-zero elements.
def moveZeroes(nums):
"""
Move all 0's to the end of the array while maintaining the relative order of non-zero elements.
Args:
nums (List[int]): List of integers.
Returns:
None: The function modifies the input list in place.
"""
# Initialize the index for the place to move the next non-zero number
last_non_zero_found_at = 0
# First pass: move all non-zero elements to the 'last_non_zero_found_at' index
for current in range(len(nums)):
if nums[current] != 0:
nums[last_non_zero_found_at] = nums[current]
last_non_zero_found_at += 1
# Second pass: fill the remaining positions with zeroes
for current in range(last_non_zero_found_at, len(nums)):
nums[current] = 0
last_non_zero_found_at index to 0. This will keep track of the position to place the next non-zero number.current.last_non_zero_found_at position and then increment last_non_zero_found_at.last_non_zero_found_at will be the index of the first position to fill with 0.0 from last_non_zero_found_at to the end of the array.This solution efficiently uses the in-place replacement strategy, ensuring minimal space usage and maintaining optimal time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?