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).
image = [[1,1,0],[1,0,1],[0,0,0]][[1,0,0],[0,1,0],[1,1,1]]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).
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.
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.
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.