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.
[1,1,0] horizontally results in [0,1,1].To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.
[0,1,1] results in [1,0,0].
Example 1:
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]]. Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]
Example 2:
Input: image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Constraints:
n == image.lengthn == image[i].length1 <= n <= 20images[i][j] is either 0 or 1.This approach involves two distinct passes over the matrix: first to flip each row horizontally by reversing the elements, and second to invert all the elements by replacing 0s with 1s and vice versa.
This C solution uses a two-pointer technique to simultaneously flip and invert each row of the binary matrix. Using XOR with 1 inverts each bit.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n^2) as each element is visited once.
Space Complexity: O(1) as no additional space proportional to input size is used.
This approach attempts to combine the flipping and inverting processes in one pass to enhance efficiency, leveraging the symmetry characteristics of the problem.
This C solution performs operations on symmetry pairs. When both elements in a pair are equal, they are inverted together, optimizing for fewer operations.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n^2) given each element may potentially be processed.
Space Complexity: O(1) since modifications are in place.
| Approach | Complexity |
|---|---|
| Two-Pass Method: Flip then Invert | Time Complexity: O(n^2) as each element is visited once. |
| Single-Pass Optimization | Time Complexity: O(n^2) given each element may potentially be processed. |
Rotate Matrix/Image by 90 Degrees | Brute - Optimal • take U forward • 324,748 views views
Watch 9 more video solutions →Practice Flipping an Image with our built-in code editor and test cases.
Practice on FleetCode