#832
Flipping an Image
EasyArrayTwo PointersBit ManipulationMatrixSimulationArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution combines the flipping and inverting operations into a single pass through each row. This reduces the number of iterations needed, making the solution more efficient.
⚙️
Algorithm
2 steps- 1Step 1: For each row, iterate through the first half of the row.
- 2Step 2: Swap the elements at the current index and its mirrored index, while simultaneously inverting their values.
solution.py8 lines
1# Full working Python code
2
3def flipAndInvertImage(image):
4 n = len(image)
5 for row in image:
6 for j in range((n + 1) // 2):
7 row[j], row[n - 1 - j] = 1 - row[n - 1 - j], 1 - row[j]
8 return imageℹ
Complexity note: The time complexity is O(n) because we only iterate through half of each row, making it more efficient than the brute force approach. The space complexity remains O(1) as we are still modifying the matrix in place.
- 1Flipping and inverting can be combined into a single operation.
- 2Understanding how to manipulate arrays in place is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.