Flipping an Image
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.
image = [[1,1,0],[1,0,1],[0,0,0]][[1,0,0],[0,1,0],[1,1,1]]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;
}
};
Explanation
The task asks for two things on each row: reverse it left-to-right, and then flip every bit (0 becomes 1, 1 becomes 0). The neat trick is doing both at the same time with two pointers, so you never need a second pass.
For each row, put one pointer i at the left end and one pointer j at the right end. Reversing means swapping the value at i with the value at j. Inverting a single bit is just value ^ 1 (XOR with 1 flips 0 to 1 and 1 to 0).
So in one step we set row[i] to row[j] ^ 1 and row[j] to row[i] ^ 1 — the swap and the flip happen together. Then we move i rightward and j leftward and repeat while i <= j. The middle cell (when i == j) just gets flipped in place.
Example: a row [1, 1, 0]. Pointers start at the ends: row[0] becomes 0 ^ 1 = 1 and row[2] becomes 1 ^ 1 = 0, giving [1, 1, 0]; then the middle 1 flips to 0, so the row ends as [1, 0, 0].
Because each row is handled in a single inward sweep, the whole matrix is processed in time proportional to its size, with no extra storage.