Flipping an Image

easy array matrix two-pointers

Problem

Given an n x n binary matrix, reverse each row and then invert it (0 becomes 1 and 1 becomes 0). Return the resulting matrix.

Inputimage = [[1,1,0],[1,0,1],[0,0,0]]
Output[[1,0,0],[0,1,0],[1,1,1]]
Reverse each row, then flip every bit.

def flipAndInvertImage(image):
    for row in image:
        i, j = 0, len(row) - 1
        while i <= j:
            row[i], row[j] = row[j] ^ 1, row[i] ^ 1
            i += 1
            j -= 1
    return image
function flipAndInvertImage(image) {
  for (const row of image) {
    let i = 0, j = row.length - 1;
    while (i <= j) {
      const tmp = row[i] ^ 1;
      row[i] = row[j] ^ 1;
      row[j] = tmp;
      i++; j--;
    }
  }
  return image;
}
class Solution {
  public int[][] flipAndInvertImage(int[][] image) {
    for (int[] row : image) {
      int i = 0, j = row.length - 1;
      while (i <= j) {
        int tmp = row[i] ^ 1;
        row[i] = row[j] ^ 1;
        row[j] = tmp;
        i++; j--;
      }
    }
    return image;
  }
}
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
    vector<vector<int>> flipAndInvertImage(vector<vector<int>>& image) {
        for (auto &row : image) {
            int i = 0, j = row.size() - 1;
            while (i <= j) {
                int tmp = row[i] ^ 1;
                row[i] = row[j] ^ 1;
                row[j] = tmp;
                i++; j--;
            }
        }
        return image;
    }
};
Time: O(n^2) Space: O(1)