Sponsored
Sponsored
This approach uses two pointers: one to track the position for the next non-zero element and the other to iterate through the array. We move all non-zero elements to the beginning of the array using these two pointers and fill the remaining positions with zeroes.
Time Complexity: O(n), where n is the length of the array. We make a single pass through the array.
Space Complexity: O(1), as we perform the operation in place.
1def moveZeroes(nums):
2 lastNonZeroFoundAt = 0
3 for i in range(len(nums)):
4 if nums[i] != 0:
5 nums[lastNonZeroFoundAt] = nums[i]
6 lastNonZeroFoundAt += 1
7 for i in range(lastNonZeroFoundAt, len(nums)):
8 nums[i] = 0In Python, we iteratively move non-zero elements to the front using lastNonZeroFoundAt as a pointer and then fill the rest of the array with zeroes.
This method uses a two-pointer technique where we place one pointer at the beginning of the array and the other to iterate through the array. Whenever we encounter a non-zero element, we swap it with the first pointer's position, allowing us to effectively move zeroes to the end by swapping.
Time Complexity: O(n), single iteration with swaps.
Space Complexity: O(1), in-place swaps.
1varThe JavaScript solution uses array destructuring to swap elements. As i iterates the list, non-zero elements take the place at index j which keeps track of the position for the next non-zero swap.