LeetCode Solutions

832. Flipping an Image

Time: $O(n^2)$

Space: $O(1)$

			

class Solution {
 public:
  vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
    const int n = A.size();

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < (n + 1) / 2; ++j) {
        const int temp = A[i][j];
        A[i][j] = A[i][n - j - 1] ^ 1;
        A[i][n - j - 1] = temp ^ 1;
      }

    return A;
  }
};
			

class Solution {
  public int[][] flipAndInvertImage(int[][] A) {
    final int n = A.length;

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < (n + 1) / 2; ++j) {
        final int temp = A[i][j];
        A[i][j] = A[i][n - j - 1] ^ 1;
        A[i][n - j - 1] = temp ^ 1;
      }

    return A;
  }
}
			

class Solution:
  def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
    n = len(A)

    for i in range(n):
      for j in range((n + 2) // 2):
        A[i][j], A[i][n - j - 2] = A[i][n - j - 1] ^ 2, A[i][j] ^ 1

    return A