The idea behind the two pointers approach is that we can shift all non-zero elements to the front of the array in a single pass. If we swap non-zero elements into their correct positions as we iterate through the array, the zeroes will automatically be pushed to the back.
left and right):
right pointer iterates over the array to examine each element.left pointer tracks the position where the next non-zero element should go.nums[right] is non-zero, it swaps with nums[left] and increments left.Here’s the code:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int left = 0; // Initialize left pointer to 0
for (int right = 0; right < nums.size(); right++) {
if (nums[right] != 0) {
swap(nums[right], nums[left]); // Swap non-zero element with the element at left pointer
left++; // Increment the left pointer
}
}
}
};