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.
1#include <vector>
2using namespace std;
3
4vector<vector<int>> flipAndInvertImage(vector<vector<int>>& image) {
5 for (auto& row : image) {
6 reverse(row.begin(), row.end());
7 for (auto& pixel : row) {
8 pixel ^= 1;
9 }
10 }
11 return image;
12}
13
14int main() {
15 vector<vector<int>> image = {{1, 1, 0}, {1, 0, 1}, {0, 0, 0}};
16 image = flipAndInvertImage(image);
17 return 0;
18}
In this C++ code, we use STL to reverse each row, and then XOR each element with 1 to invert it.
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#
This C solution performs operations on symmetry pairs. When both elements in a pair are equal, they are inverted together, optimizing for fewer operations.