DSA AnimatorDSA animations
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).

How to solve Flipping an Image

LeetCode 832 · Easy · Arrays · Pattern: 2D Array

Why the obvious approach is slow

You could reverse each row in one pass, then invert it in another. Both steps can happen together, in a single pass from both ends.

The key idea

Swap the values at the left and right ends of the row, and invert both while you swap. Move the two ends inward until they meet. If they meet on the middle cell, just invert that one.

Remember

Reverse means two pointers swapping from both ends. Inverting a bit is x exclusive or 1, and it can be done during the swap.

Run the animation above on your own input, or watch the 1:38 video explanation of Flipping an Image with a dry run and Java code.

More Arrays problems