Sponsored
Sponsored
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.
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.
1function flipAndInvertImage(image) {
2 for (let row of image) {
3 let start = 0, end = row.length - 1;
4 while (start <= end) {
5 [row[start], row[end]] = [row[end] ^ 1, row[start] ^ 1];
6 start++;
7 end--;
8 }
9 }
10 return image;
11}
12
13// Example usage
14let image = [[1,1,0], [1,0,1], [0,0,0]];
15console.log(flipAndInvertImage(image));
In JavaScript, the solution adopts a two-pointer approach to reverse and then invert each row, using XOR for inversion.
This approach attempts to combine the flipping and inverting processes in one pass to enhance efficiency, leveraging the symmetry characteristics of the problem.
Time Complexity: O(n^2) given each element may potentially be processed.
Space Complexity: O(1) since modifications are in place.
1#include <vector>
using namespace std;
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& image) {
for (auto& row : image) {
int n = row.size();
for (int j = 0; j < (n + 1) / 2; ++j) {
if (row[j] == row[n - 1 - j]) {
row[j] ^= 1;
row[n - 1 - j] ^= 1;
}
}
}
return image;
}
int main() {
vector<vector<int>> image = {{1, 1, 0}, {1, 0, 1}, {0, 0, 0}};
image = flipAndInvertImage(image);
return 0;
}
In this C++ implementation, the solution focuses on leveraging symmetry. Two elements equidistant from the center are considered together, and both are flipped and inverted simultaneously if identical.