832. Flipping an Image
easyFlip a binary matrix horizontally then invert every bit. The two-pointer per-row trick fuses both passes into a single XOR-and-swap loop.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image. To flip an image horizontally means that each row of the image is reversed. To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.
Constraints
n == image.lengthn == image[i].length1 <= n <= 20images[i][j] is either 0 or 1.
Examples
Example 1
image = [[1,1,0],[1,0,1],[0,0,0]][[1,0,0],[0,1,0],[1,1,1]]Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]]. Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]
Example 2
image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]][[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
Doing flip then invert as two separate passes is fine but wastes work — the inversion is just XOR with 1.
Hint 2
Fuse: for each row, two pointers from outside in. Swap and XOR each end with 1 in one step.
Hint 3
Edge case: the middle element of an odd-length row swaps with itself but still needs the XOR.
Solution approach
Reveal approach
Two-pointer per-row fused pass. For each row in image, set i = 0 and j = n - 1. While i < j: temp = row[i] ^ 1; row[i] = row[j] ^ 1; row[j] = temp; advance i and retreat j. If i == j (odd-length row, single middle element), do row[i] ^= 1 to invert that lone element. The XOR-with-1 is the inversion (0 → 1, 1 → 0) and the swap is the horizontal flip — fused into one statement so we only touch each cell once. O(n^2) time over the whole matrix, O(1) extra space (in-place).
Complexity
- Time
- O(n^2)
- Space
- O(1)
Related patterns
- two-pointers
- bit-manipulation
Related problems
- 344. Reverse String
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Microsoft
Practice these live with InterviewChamp.AI
Drill Flipping an Image and Bit Manipulation problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →