Flip and Invert Image

Given a binary matrix image, flip each row horizontally and then invert (0→1, 1→0). Return the resulting image.

Example 1
Input: [[1,1,0],[1,0,1],[0,0,0]] → Output: [[1,0,0],[0,1,0],[1,1,1]]
Example 2
Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] → Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]

Solution Approach

For each row, use two pointers from both ends. Swap elements while XOR-ing with 1 to flip and invert simultaneously. When pointers meet at the middle (odd length), just flip the middle element.

  • Use two pointers lo and hi for each row.
  • While lo < hi: swap arr[lo] and arr[hi] and XOR both with 1.
  • When lo == hi (middle of odd-length row): flip arr[lo] ^= 1.
  • Process all rows.
Java
class Solution {
    public int[][] flipAndInvertImage(int[][] image) {
        for (int[] row : image) {
            int lo = 0, hi = row.length - 1;
            while (lo <= hi) {
                int tmp = row[lo] ^ 1;
                row[lo] = row[hi] ^ 1;
                row[hi] = tmp;
                lo++; hi--;
            }
        }
        return image;
    }
}
  • Time Complexity: O(M*N)
  • Space Complexity: O(1) in-place