Problem Description
Given an n x n binary matrix image, flip the image horizontally (i.e., reverse each row) and then invert it by changing each 0 to 1 and each 1 to 0.
Key Insights
- Each row is processed independently.
- Flipping horizontally involves reversing the elements in a row.
- Inverting each bit can be efficiently done using XOR with 1.
- A two-pointer approach can combine both flipping and inverting in a single pass.
Space and Time Complexity
Time Complexity: O(n²) because we process each element in the n x n matrix.
Space Complexity: O(1) since the operations are performed in-place with no extra space usage.
Solution
We use a two-pointer approach to simultaneously flip and invert each row of the image. For each row, initialize two pointers (left and right). As you swap the elements at these pointers, invert them with an XOR operation. This handles even and odd sized rows in one pass, ensuring that the middle element for odd-length rows is also inverted properly.