File: flipping-an-image/solution.py

Date: 2026-06-06

Time: 16:53

flipping-an-image/solution.py

Purpose

This file solves LeetCode 832 — Flipping an Image. Given an n x n binary matrix, it flips each row horizontally (reverses it), then inverts every value (0 → 1, 1 → 0). The file owns this single transformation and exposes it via the standard Solution class that LeetCode and the project's test harness expect.

Key Components

Solution.flipAndInvertImage(self, image: list[list[int]]) -> list[list[int]]

The only method. It mutates the input matrix in-place and also returns it — matching LeetCode's convention where the return value is the same object.

Patterns

Fused reverse-and-invert via two-pointer swap. The clever move here is that the reverse and invert are not done as separate passes. Instead, a single while lo <= hi loop does both at once:


row[lo], row[hi] = row[hi] ^ 1, row[lo] ^ 1

This simultaneously swaps row[lo] and row[hi] (the reverse) and XORs each with 1 (the invert). When lo == hi (the middle element in an odd-length row), the element is XORed with 1 twice in the same assignment — but since row[lo] and row[hi] refer to the same position, the value is read once and written once, so it's correctly inverted exactly once.

In-place mutation. No new lists are allocated. The method modifies the input matrix directly, which is O(1) extra space.

Dependencies

Imports: None — pure standard-library Python with no external dependencies.

Imported by: The project's flipping-an-image/test_solution.py imports and tests this class. The long "Imported By" list in the prompt is an artifact of the repo's test infrastructure — those other test files don't actually depend on this solution; they share a common test harness pattern.

Flow

1. Iterate over each row in image.

2. Initialize two pointers: lo = 0, hi = len(row) - 1.

3. While lo <= hi, swap-and-invert the elements at both ends, then move the pointers inward.

4. After all rows are processed, return the (now mutated) image.

For a 3×3 matrix like [[1,1,0],[1,0,1],[0,0,0]]:

Invariants

Error Handling

None. The method trusts its input conforms to the problem constraints. No validation, no exceptions. This is typical for LeetCode solutions in this repo.