INTUITION:

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.

APPROACH:

Time Complexity:O(N)

Space Complexity:O(1)

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
            }
        }
    }
};

KEYPOINTS: