Flipping an Image — LeetCode 832 Python Solution

EasyBit ManipulationArrayTwo PointersMatrixSimulation
Problem
#832
Reading time
2 min

The problem

Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image. To flip an image horizontally means that each row of the image is reversed.

Example

Input
image = [[1,1,0],[1,0,1],[0,0,0]]
Output
[[1,0,0],[0,1,0],[1,1,1]]
Explanation
First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].

Python solution

Python
class Solution:
    def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
        n = len(image)
        for row in image:
            i, j = 0, n - 1
            while i < j:
                if row[i] == row[j]:
                    row[i] ^= 1
                    row[j] ^= 1
                i, j = i + 1, j - 1
            if i == j:
                row[i] ^= 1
        return image

Complexity

MeasureComplexity
TimeO(n^2), where n is the number of rows or columns in the matrix
SpaceO(1) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 832. Flipping an Image is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 832. Flipping an Image?
LeetCode 832. Flipping an Image is rated Easy on LeetCode.
What topics does LeetCode 832. Flipping an Image cover?
LeetCode 832. Flipping an Image is tagged Bit Manipulation, Array, Two Pointers, Matrix and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview