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]

Constraints

  • n == image.length
  • n == image[i].length
  • 1 ≤ n ≤ 20
  • image[i][j] is either 0 or 1

Visualization

Tap to expand
Flipping an Image - Optimal Solution INPUT n x n Binary Matrix 1 1 0 1 0 1 0 0 0 Row 0 Row 1 Row 2 Input Array: [[1,1,0], [1,0,1], [0,0,0]] = 1 (Black) = 0 (White) ALGORITHM STEPS 1 Iterate Each Row Process rows one by one 2 Flip Horizontally Reverse each row [1,1,0] --> [0,1,1] 3 Invert Values 0 becomes 1, 1 becomes 0 [0,1,1] --> [1,0,0] 4 Optimization Combine flip + invert: XOR with 1 while swapping result[i][j] = image[i][n-1-j] XOR 1 FINAL RESULT Transformed Matrix 1 0 0 0 1 0 1 1 1 Output Array: [[1,0,0], [0,1,0], [1,1,1]] OK - Complete! Time: O(n^2) | Space: O(1) Key Insight: Flip + Invert can be done in one pass using XOR! For each pair of elements at positions i and (n-1-i), swap them and XOR each with 1. This combines both operations efficiently. If flipping keeps the same element (middle of odd-length row), just XOR it with 1. Think: photo negative + pancake flip in one move! TutorialsPoint - Flipping an Image | Optimal Solution
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