Flipping an Image — Solution in Python, Java & C++
Flipping an Image solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on arrays and matrix.
Flipping an Image is an easy coding problem on arrays, matrix and two pointers, asked in Amazon, Google and Adobe interviews.
- Difficulty: Easy
- Topics: Arrays, Matrix, Two Pointers, Simulation
- Asked at: Amazon, Google, Adobe
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given an n × n binary matrix image, flip it horizontally (reverse each row), then invert it (swap every 0 and 1), and return the result.
Example 1
Input: image = [[1,1,0],[1,0,1],[0,0,0]]
Output: [[1,0,0],[0,1,0],[1,1,1]]
Example 2
Input: image = [[1,0]]
Output: [[1,0]]
Explanation: Reversing gives [0,1], and inverting gives [1,0].
Example 3
Input: image = [[0]]
Output: [[1]]
Constraints
1 <= image.length <= 8image[i].length == image.lengthimage[i][j] is 0 or 1.
Hints for Flipping an Image
Hint 1
Both steps can happen in one pass: read the row from the right and write
1 - value.Hint 2
In place with two pointers: swap the ends, inverting both — and when they meet, invert that middle cell once.
How to solve Flipping an Image
Reverse each row and invert every bit in the same pass by reading from the right and writing 1 - value.
Approach
- For each row, build the new row from
reversed(row)with each value mapped to1 - v.
Why it works
Flipping and inverting commute, so combining them into one traversal is safe.
Complexity
- Time —
O(n²) - Space —
O(n²) for the output (O(1) in place)
Pitfalls
- In place, swap the ends inverting both and, when the pointers meet on a middle cell, invert it exactly once.
Reference solution
Python
def flipAndInvertImage(image):
return [[1 - v for v in reversed(row)] for row in image]Java
public static int[][] flipAndInvertImage(int[][] image) {
int n = image.length;
int[][] out = new int[n][];
for (int i = 0; i < n; i++) {
int cols = image[i].length;
out[i] = new int[cols];
for (int j = 0; j < cols; j++) out[i][j] = 1 - image[i][cols - 1 - j];
}
return out;
}C++
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& image) {
vector<vector<int>> out;
for (size_t i = 0; i < image.size(); i++) {
vector<int> row;
for (int j = (int) image[i].size() - 1; j >= 0; j--) row.push_back(1 - image[i][j]);
out.push_back(row);
}
return out;
}JavaScript
var flipAndInvertImage = function(image) {
const out = [];
for (let i = 0; i < image.length; i++) {
const row = [];
for (let j = image[i].length - 1; j >= 0; j--) row.push(1 - image[i][j]);
out.push(row);
}
return out;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 1199 arrays problems · the whole catalogue
Learn the technique: Arrays · Matrix and Grid Traversal