πŸ“ Problem Details

πŸ’­What Were My Initial Thoughts?

- two pointers from both points for each row, swap and flip the bits using XOR

πŸ’‘ Explanation of Solution

- iterate through each row using lef tand right pointers
- swap the elements while simultaneously flipping them (0 <--> 1)
- use XOR operation for flipping bits
- continue until left >= right to account for odd elements

βŒ› Complexity Analysis

Time Complexity: O(n)
Space Complexity: O(1)

πŸ’» Implementation of Solution

class Solution {
public:
    vector<vector<int>> flipAndInvertImage(vector<vector<int>>& image) {
        int n = image.size();
        
        for (auto& row : image) {
            int left = 0, right = n - 1;
            while (left <= right) {
                // Swap and flip bits using XOR
                swap(row[left], row[right]);
                row[left] ^= 1;  // Flip left bit
                if (left != right) row[right] ^= 1;  // Flip right bit
                left++, right--;
            }
        }
 
        return image;
    }
};