Flipping an Image
Easy · Matrix · Array · Two Pointers · Bit Manipulation · Matrix · Simulation
Problem
You are given an n x n binary matrix image. Transform it in two steps and return the result:
- Flip every row horizontally, so it reads right to left: row [1,1,0] becomes [0,1,1].
- Invert every value: each 0 becomes 1 and each 1 becomes 0.
You may change image in place and return it, or return a new matrix.
Examples
Input: image = [[1,0,0],[1,1,0],[0,1,0]] Output: [[1,1,0],[1,0,0],[1,0,1]]
Flipping gives [[0,0,1],[0,1,1],[0,1,0]], and inverting that gives the output.
Input: image = [[0,1],[1,1]] Output: [[0,1],[0,0]]
The flipped rows are [1,0] and [1,1], which invert to [0,1] and [0,0].
Input: image = [[1]] Output: [[0]]
Flipping one cell changes nothing; inverting turns 1 into 0.
Constraints
- n == len(image) == len(image[i])
- 1 <= n <= 20
- image[i][j] is 0 or 1
Approaches
- Baseline: reverse, then invert, into new matrices — time O(n²), space O(n²)
Follow-up
Notice that when row[j] != row[n-1-j], flipping swaps two different bits and inverting swaps them back: that pair ends up unchanged. Only pairs of equal bits change, and both flip. So the whole job is: for each mirrored pair of equal bits, invert both; leave unequal pairs alone.
Related problems
Start free on Cariara · Coding problems · System design studio