Flipping an Image — LeetCode 832 Python Solution
- Problem
- #832
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
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
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 imageComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2), where n is the number of rows or columns in the matrix |
| Space | O(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.