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.
1var moveZeroes = function(nums) {
2 let lastNonZeroFoundAt = 0;
3 for (let i = 0; i < nums.length; i++) {
4 if (nums[i] !== 0) {
5 nums[lastNonZeroFoundAt++] = nums[i];
6 }
7 }
8 for (let i = lastNonZeroFoundAt; i < nums.length; i++) {
9 nums[i] = 0;
10 }
11};The JavaScript solution follows the same logic. We increment lastNonZeroFoundAt every time we assign a non-zero value to its position and set the remaining positions to zero.
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.
1The Python version leverages tuple unpacking to swap elements at positions j and i. The j pointer ensures that swaps occur only with zeros, keeping all non-zero elements ordered.