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.
1public class Solution {
2 public int[][] FlipAndInvertImage(int[][] image) {
3 foreach (var row in image) {
4 int start = 0, end = row.Length - 1;
5 while (start <= end) {
6 int temp = row[start] ^ 1;
7 row[start] = row[end] ^ 1;
8 row[end] = temp;
9 start++;
10 end--;
11 }
12 }
13 return image;
14 }
15
16 static void Main(string[] args) {
17 int[][] image = new int[][] { new int[] {1, 1, 0}, new int[]{1, 0, 1}, new int[]{0, 0, 0} };
18 Solution solution = new Solution();
19 solution.FlipAndInvertImage(image);
20 }
21}
In C#, this solution leverages a two-pointer technique to achieve both flipping and inversion in a single pass per row. XOR is used 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.
1function
The optimized JavaScript solution processes each row by analyzing symmetry, inverting only when necessary, for fewer operation cycles.