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]
The main strategy involves two pointers:
lastNonZeroFoundAt
: Tracks the position to place the next non-zero element.current
: Loops through all elements in the array.Algorithm:
current
. For every non-zero element nums[current]
:
nums[lastNonZeroFoundAt]
.lastNonZeroFoundAt
.lastNonZeroFoundAt
is positioned at the first zero.Here is the Java implementation:
public class Solution {
public void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0) return;
int lastNonZeroFoundAt = 0;
// Move all the non-zero elements forward
for (int current = 0; current < nums.length; current++) {
if (nums[current] != 0) {
// Swap the elements
int temp = nums[lastNonZeroFoundAt];
nums[lastNonZeroFoundAt] = nums[current];
nums[current] = temp;
lastNonZeroFoundAt++;
}
}
}
}
In conclusion, this two-pointer technique efficiently moves all zeroes to the end while maintaining the order of non-zero elements.
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?