Flipping an Image (LeetCode 832): Solution and Explanation

Easy
Array
Two pointers
Bit manipulation
Matrix
Simulation

Given an n x n binary image, reverse every row (a horizontal flip) and then toggle every bit (an invert). Return the resulting image. The work can be done in place in a single pass over each row.

Intuition

The literal approach does two passes: reverse each row, then walk it again and replace every bit with 1 - bit. That is already linear in the number of cells, so it is fine, but it touches every cell twice.

Look at where a value ends up. After the flip, position i holds what used to be at position n - 1 - i. After the invert, it holds the opposite of that. So the final row[i] is just old row[n - 1 - i] ^ 1, and symmetrically the final row[n - 1 - i] is old row[i] ^ 1.

That means each mirror pair can be finished in one move: swap the two values and toggle both. Two pointers walking in from the ends visit each pair once.

When the row has odd length the pointers meet on the middle cell. A flip leaves that cell where it is, so it only needs to be inverted, and the same swap-and-toggle code already does exactly that when i == j.

Approach: Two pointers per row

  1. For each row, set i = 0 and j = n - 1.
  2. While i <= j, assign row[i], row[j] = row[j] ^ 1, row[i] ^ 1. In languages without tuple assignment, save row[i] in a temporary first.
  3. Move i right and j left.
  4. After all rows are processed, return the image.

Step-by-step example

image = [[1,1,0],[1,0,1],[0,0,0]]
  1. Row 0 = [1,1,0]. i = 0, j = 2: swap 1 and 0 and invert both, giving row[0] = 0 ^ 1 = 1 and row[2] = 1 ^ 1 = 0. Row is [1,1,0].
  2. Row 0, i = j = 1: the middle 1 is only inverted to 0. Row 0 is now [1,0,0].
  3. Row 1 = [1,0,1]. The pair (1, 1) becomes (0, 0), and the middle 0 becomes 1. Row 1 is [0,1,0].
  4. Row 2 = [0,0,0]. The pair becomes (1, 1) and the middle becomes 1. Row 2 is [1,1,1].
  5. The result is [[1,0,0],[0,1,0],[1,1,1]].

Code: Python, Java, C++

1class Solution:
2    def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
3        for row in image:
4            i, j = 0, len(row) - 1
5            while i <= j:
6                row[i], row[j] = row[j] ^ 1, row[i] ^ 1
7                i += 1
8                j -= 1
9        return image
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

There are n rows, and each row is processed in about n / 2 pair operations, so every one of the n^2 cells is written once.

Space

O(1)

The image is modified in place and only the two pointer indices are stored.

Other approaches

Reverse, then invert (time O(n^2), space O(1))

Call the language's reverse on each row and then map every bit to 1 - bit. Same complexity and very readable, at the cost of two passes per row.

Build a new matrix (time O(n^2), space O(n^2))

Create result[r][c] = 1 - image[r][n - 1 - c] directly. Easy to reason about, but it allocates a second n x n matrix.

Common mistakes

  • Using i < j as the loop condition. On odd-length rows the middle cell is then never inverted.
  • Overwriting row[i] before reading it for row[j]. Without tuple assignment you need a temporary variable.
  • Inverting with ~x. In most languages that gives -1 or -2, not 0 or 1. Use x ^ 1 or 1 - x.
  • Inverting each pair twice, once in a swap helper and again in a second pass.

Frequently asked questions

Does it matter whether you flip first or invert first?

No. Reversing a row and toggling every bit are independent operations, so doing them in either order gives the same image.

What happens to the middle cell of an odd-length row?

Flipping keeps it in place, so it is only inverted. With the i <= j loop, the swap-and-toggle line reads and writes the same cell, which inverts it once.

Can a pair that is already different be skipped?

Yes. If row[i] != row[j], swapping and inverting both gives back the same two values, so only equal pairs actually change. It is a neat observation but does not improve the O(n^2) bound.

What is the time and space complexity of Flipping an Image?

O(n^2) time, since every cell is written once, and O(1) extra space because the image is updated in place.