π§© Problem Description
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: [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Constraints:
Do this in-place without making a copy of the array.
Minimize the total number of operations.
π‘ Solution: Two Pointers
π± Core Idea
Use two pointers to iterate through the array:
right pointer: scans through the array to find non-zero elements.
left pointer: tracks the position where the next non-zero element should be placed.
π§ Strategy
Traverse the array with right.
When nums[right] != 0:
Swap nums[right] with nums[left].
Move left one step to the right.
Continue until the end of the array.
This approach ensures all non-zero elements are moved to the front in order, and the leftover positions are filled with 0s.
π§ͺ Step-by-Step Example
Given nums = [0, 1, 0, 3, 12], letβs walk through:
Initial: [0, 1, 0, 3, 12]
left = 0, right = 0 β nums[0] is 0 β do nothing
right = 1 β nums[1] = 1 β 0 β swap nums[0] and nums[1]
β [1, 0, 0, 3, 12], left++
right = 2 β nums[2] = 0 β do nothing
right = 3 β nums[3] = 3 β swap nums[1] and nums[3]
β [1, 3, 0, 0, 12], left++
right = 4 β nums[4] = 12 β swap nums[2] and nums[4]
β [1, 3, 12, 0, 0], left++
β Final result: [1, 3, 12, 0, 0]
π§Ύ Code (Java)
class Solution {
public void moveZeroes(int[] nums) {
int n = nums.length, left = 0, right = 0;
while (right < n) {
if (nums[right] != 0) {
swap(nums, left, right);
left++;
}
right++;
}
}
private void swap(int[] nums, int i, int j) {
if (i == j) return; // Optional: skip unnecessary swaps
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}