1. Problem Summary
You are given a binary matrix image where each entry is either:
0 or 1
Your task is to transform the matrix by performing two operations on each row:
- Flip horizontally
This means reversing each row, so first element becomes last, etc. - Invert
Replace:0 → 1 1 → 0
Finally, return the resulting matrix.
Example interpretation:
If a row is:
[1, 0, 0]
After flipping:
[0, 0, 1]
After inverting:
[1, 1, 0]
2. Key Insights
Flip and invert can be combined in one pass
Instead of first reversing and then scanning again to invert, you can:
- swap elements from both ends
- invert during the swap
- if left meets right (odd length), just invert once
Inversion formula
A simple and fast way to invert a bit:
bit ^ 1 (XOR with 1)
Matrix constraints are small enough
But optimal in-place solution is still expected.
Each row is processed independently
No cross-row dependency exists.
3. Approach
In-place flip + invert using two pointers
Steps:
- Loop through each row in image.
- Set two pointers:
left = 0 right = row.length - 1 - While left ≤ right:
- If left == right (middle element):
invert row[left] - Else:
- swap row[left] and row[right]
- invert both values
- move pointers inward
- If left == right (middle element):
- After all rows processed, return image.
This performs both operations at once.
4. Time and Space Complexity
Time Complexity: O(N × M)
Each element touched once.
Space Complexity: O(1)
Performed in-place with no additional storage.
5. Java Solution
class Solution {
public int[][] flipAndInvertImage(int[][] image) {
int rows = image.length;
int cols = image[0].length;
for (int r = 0; r < rows; r++) {
int left = 0;
int right = cols - 1;
while (left <= right) {
if (left == right) {
image[r][left] ^= 1; // invert
} else {
int temp = image[r][left] ^ 1; // invert while swapping
image[r][left] = image[r][right] ^ 1;
image[r][right] = temp;
}
left++;
right--;
}
}
return image;
}
}
6. Dry Run Examples
Example 1
Input:
[ [1,1,0], [1,0,1], [0,0,0] ]
Row 1: [1,1,0]
Flip → [0,1,1]
Invert → [1,0,0]
Row 2: [1,0,1]
Flip → [1,0,1]
Invert → [0,1,0]
Row 3: [0,0,0]
Flip → [0,0,0]
Invert → [1,1,1]
Output:
[ [1,0,0], [0,1,0], [1,1,1] ]
Example 2
Input:
[ [1] ]
Flip → [1]
Invert → [0]
Output:
[ [0] ]
Example 3
Input:
[ [0,1], [1,1] ]
Row 1:
Flip → [1,0]
Invert → [0,1]
Row 2:
Flip → [1,1]
Invert → [0,0]
Output:
[ [0,1], [0,0] ]
7. Why This Solution Works
- Processes matrix in-place efficiently
- Combines two operations into a single pass
- Uses XOR to invert bits cleanly
- Works for odd and even row lengths
- Minimizes overhead and branching
- Matches intended problem behavior exactly
8. Common Mistakes
- Performing full flip first, then full invert (still correct but slower)
- Forgetting to handle middle element in odd-length rows
- Using extra arrays unnecessarily
- Misinterpreting flip direction
- Using if-else to invert instead of XOR (verbose)
