← 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 — Flip + XOR Invert in One Pass
Use L and R pointers. If nums[L]≠nums[R], flipping and inverting cancel out — no change. If they're equal, both need XOR 1. When L=R (middle), always XOR 1. O(n) per row.
Current Row
Variables
Row
L pointer
R pointer
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, use two pointers: L=0, R=n-1
2
If row[L] == row[R]: XOR both with 1 (flip + invert both)
3
If row[L] ≠ row[R]: flip+invert cancel each other — skip
4
If L == R (middle): always XOR 1 (only invert, flip does nothing)
Time
O(n²)
Space
O(1)
Why It Works

Flip reverses the row, invert flips each bit. When L≠R: one is 0, one is 1. Flipping swaps them, inverting flips them back — net effect is zero change. When L=R: flip does nothing, just invert. When L=R and both same value — XOR both with 1.