Flipping an Image (LeetCode 832): Reverse and Invert in One Pass

Author: 7755ec0fdd

04 November 2026

Views: 7

Given a binary matrix, reverse each row horizontally, then invert it (0 becomes 1, 1 becomes 0). Return the result.

Idea

Use two pointers per row. For positions i and j that swap, the new values are the inverted old values from the opposite side. When row[i] != row[j], swapping and inverting leaves the row unchanged, so you only touch pairs that are equal.

def flipAndInvertImage(image):
for row in image:
i, j = 0, len(row) - 1
while i <= j:
if row[i] == row[j]:
row[i] ^= 1
if i != j:
row[j] ^= 1
i += 1
j -= 1
return image

Complexity

O(m*n) time, O(1) extra space.

Interview notes

Start with the obvious version, [[1 - x for x in reversed(row)] for row in image], then show the in-place one and explain the "unequal pairs stay put" observation. Watch the middle element when the row length is odd.

If you want to rehearse explaining solutions like this under time pressure, https://www.linkjob.ai/ is something I help build (disclosure: I work on Linkjob AI).


Edit Code:

Please enter an edit code

Edit codes must be at least 20 characters

Share