Python 0832.py
class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
for y in range(len(image)):
for x in range(len(image[y])):
image[y][x] ^= 1
image[y] = reversed(image[y])
return image
Difficulty
and has an acceptance rate of about 84% (600k+ submissions).
Typical patterns to solve this problem:
- Array
- Bit Manipulation
- Matrix
- Simulation
- Two Pointers
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method that transforms a binary matrix by performing two operations on each row: a bitwise inversion of every element followed by a horizontal reversal. The method works directly on the input matrix, mutating it in place and finally returning the same reference.
Key Steps
Row Traversal
for y in range(len(image)):
The outer loop walks through each row index y of the matrix. By using range(len(image)) the code safely handles matrices of any height, including an empty matrix where the loop body is never executed.
Element-wise Inversion
for x in range(len(image[y])):
image[y][x] ^= 1
Inside the row loop, a second loop iterates over each column index x. The expression image[y][x] ^= 1 flips the binary value using the XOR-assignment operator. Because the matrix contains only 0 and 1, XOR with 1 reliably produces the opposite bit, achieving the inversion without a conditional statement.
Row Reversal
image[y] = reversed(image[y])
After all elements in the current row have been inverted, the row is replaced with a reversed view created by the built-in reversed function. This operation changes the order of elements from left-to-right to right-to-left, completing the horizontal flip for that row.
Return Value
return image
The method concludes by returning the mutated matrix. Since the transformation is performed in place, the returned reference points to the same object that was passed in.
Edge Cases Handled
When the input matrix is empty ([]), the outer loop has no iterations, so the method immediately returns the empty list unchanged. A matrix with a single row is processed by the same loops; the inner inversion loop runs over the sole rowβs elements, and the reversal step yields a reversed iterator that, when assigned back, produces the correctly flipped row. A single-column matrix also works because the inner loop iterates over the lone element, inverts it, and the reversal of a one-element sequence leaves the order unchanged, which is the expected result for a horizontal flip.
Performance Optimizations
The algorithm modifies the original matrix rather than allocating a new one, which reduces memory overhead. Using the XOR-assignment operator for inversion eliminates the need for an explicit conditional branch, allowing the Python interpreter to execute a single bytecode instruction per element. The reversed built-in returns an iterator that does not create an intermediate list; assigning this iterator back to the row replaces the row with a lazy view that is materialized only when accessed later, avoiding an extra copy of the row data. Together, these choices keep the runtime work proportional to the number of elements while minimizing auxiliary allocations.
ELI5 - Simplified Explanation
Imagine you have a row of square tiles that are either black or white. Some are zeros and some are ones. This collection of tiles is what the computer calls an image. The code looks at every row inside this image one by one.
Inside each row, the computer visits every single tile. It plays a little game of switcheroo with the colors. If a tile is a zero, it changes to a one, and if it is a one, it changes to a zero. It treats the zero as a closed door and the one as an open door. By swapping them, all the ones become zeros and all the zeros become ones.
After all the tiles in a row have been swapped, the computer picks up the entire row and flips it around backwards. The tile that was at the very start of the line moves to the very end, and the last one takes the place of the first. This happens for every single row in the image until every line has been swapped and flipped.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | JS | Go | ||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality