← Back to DSA Animator
Flipping an Image LC #832 Easy Array Basics · Bit Manipulation
Problem

Given an n×n binary matrix image, flip each row horizontally and invert it. To flip: reverse each row. To invert: replace 0→1, 1→0 (XOR with 1).

Example 1
Input: image = [[1,1,0],[1,0,1],[0,0,0]]
Output: [[1,0,0],[0,1,0],[1,1,1]]
Explanation: Flip [1,1,0]→[0,1,1]→invert→[1,0,0].
Constraints: n == image.length == image[i].length  |  1≤n≤20  |  image[i][j] ∈ {0,1}
Try Examples
Custom:
Approach
Two Pointers — Swap + XOR Invert in One Pass
For each row: temp = L^1; L = R^1; R = temp. This swaps and inverts both endpoints simultaneously. When L==R (middle), just inverts. O(n²) time, O(1) space.
Full Matrix View Original Image
Init
↔ Flip
⚡ Swap+Invert
✓ Done
L pointer R pointer Row active Middle (L=R) Processed
Current Row — Pointer Detail
Variables
Row i
left
right
Operation
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
For each row i, init left=0, right=n-1
2
temp = image[i][left] ^ 1  (invert left, save)
3
image[i][left] = image[i][right] ^ 1  (put inverted right in left slot)
4
image[i][right] = temp  (put inverted left in right slot)
5
left++, right-- — repeat until pointers meet
Time
O(n²)
Space
O(1)
Why It Works

The trick: flip (reverse) + invert (XOR 1) can be fused. For endpoints L and R:

L ≠ R values: temp=L^1, L=R^1, R=temp. Since L and R are opposite bits, swapping+inverting each gives back the original values — net zero change.

L = R values: same as above but now L^1 ≠ L, so both actually change — both get XOR'd.

L = R (middle): same cell written twice — final result is XOR 1 (invert).