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
๐ŸŽฏ Photo Lab Analogy: Flip and Invert Process๐Ÿ“ท Original PhotoBlack = 1, White = 0๐Ÿชž Mirror FlipHorizontally Flipped๐ŸŽž Create NegativeInverted Colors๐Ÿ”ง Two-Pointer OptimizationInstead of doing this in two separate steps, we can combine them!Use two pointers: one at the start, one at the end of each rowSwap the elements AND invert them simultaneously in one passThis reduces our algorithm from 2 passes to just 1 pass through the matrix!๐Ÿ’ก Key Insight: Combine flip and invert operations for optimal efficiency
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

n
2n
โš  Quadratic Growth
Space Complexity
O(1)

In-place transformation with only constant extra space for pointers

n
2n
โœ“ Linear Space

Constraints

  • n == image.length
  • n == image[i].length
  • 1 โ‰ค n โ‰ค 20
  • image[i][j] is either 0 or 1
Asked in
Google 25 Amazon 18 Apple 15 Microsoft 12
95.0K Views
Medium Frequency
~8 min Avg. Time
2.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen