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