Flipping an Image - Problem
You're given an n x n binary matrix representing a black and white image. Your task is to flip the image horizontally, then invert it, and return the resulting image.
What does "flip horizontally" mean?
Each row of the image is reversed. For example, flipping [1,1,0] horizontally results in [0,1,1].
What does "invert" mean?
Each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0,1,1] results in [1,0,0].
Think of this like taking a photo negative and then flipping it like you would flip a pancake!
Input & Output
example_1.py โ Basic 3x3 matrix
$
Input:
image = [[1,1,0],[1,0,1],[0,0,0]]
โบ
Output:
[[1,0,0],[0,1,0],[1,1,1]]
๐ก Note:
First flip: [[0,1,1],[1,0,1],[0,0,0]], then invert: [[1,0,0],[0,1,0],[1,1,1]]
example_2.py โ 4x4 matrix
$
Input:
image = [[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]]
๐ก Note:
Each row is flipped horizontally then inverted: [1,1,0,0] โ [0,0,1,1] โ [1,1,0,0]
example_3.py โ Single element
$
Input:
image = [[1]]
โบ
Output:
[[0]]
๐ก Note:
Single element matrix: flip [1] โ [1], then invert [1] โ [0]
Visualization
Tap to expand
Understanding the Visualization
1
Original Photo
Start with your black and white photograph
2
Mirror Flip
Hold the photo up to a mirror - everything is reversed horizontally
3
Create Negative
Convert to negative - all black areas become white, white areas become black
4
Final Result
You now have a horizontally flipped negative of the original image
Key Takeaway
๐ฏ Key Insight: By using two pointers and combining both operations (flip + invert) in a single pass, we achieve optimal efficiency while maintaining clean, readable code.
Time & Space Complexity
Time Complexity
O(nยฒ)
We still visit each element once, but in a single pass through the nรn matrix
โ Quadratic Growth
Space Complexity
O(1)
In-place transformation with only constant extra space for pointers
โ Linear Space
Constraints
- n == image.length
- n == image[i].length
- 1 โค n โค 20
- image[i][j] is either 0 or 1
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code