Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Flip the matrix horizontally and invert it using JavaScript
We are required to write a JavaScript function that takes in a 2-D binary array (an array that consists of only 0 or 1) as the first and only argument.
Our function should first flip the matrix horizontally, then invert it, and return the resulting matrix.
Understanding the Operations
To flip the matrix horizontally means that each row of the matrix is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].
To invert a matrix means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0].
Input and Expected Output
// Input
const arr = [
[1, 1, 0],
[1, 0, 1],
[0, 0, 0]
];
// Expected Output
const output = [
[1, 0, 0],
[0, 1, 0],
[1, 1, 1]
];
Step-by-Step Process
First we reverse each row:
[[0,1,1],[1,0,1],[0,0,0]]
Then, we invert the matrix:
[[1,0,0],[0,1,0],[1,1,1]]
Method 1: In-Place Flip and Invert
This approach modifies the original matrix by combining both operations in a single pass:
const arr = [
[1, 1, 0],
[1, 0, 1],
[0, 0, 0]
];
const flipAndInvert = (arr = []) => {
const invert = n => (n === 1 ? 0 : 1);
for(let i = 0; i < arr.length; i++) {
for(let j = 0; j < arr[i].length / 2; j++) {
const index2 = arr[i].length - 1 - j;
if(j === index2) {
// Middle element in odd-length row
arr[i][j] = invert(arr[i][j]);
} else {
// Swap and invert both elements
const temp = arr[i][j];
arr[i][j] = invert(arr[i][index2]);
arr[i][index2] = invert(temp);
}
}
}
return arr;
};
console.log(flipAndInvert(arr));
[ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 1, 1, 1 ] ]
Method 2: Separate Operations
This approach performs flip and invert as separate steps for better readability:
const arr2 = [
[1, 1, 0],
[1, 0, 1],
[0, 0, 0]
];
const flipAndInvertSeparate = (matrix) => {
// Step 1: Flip horizontally
for(let i = 0; i < matrix.length; i++) {
matrix[i].reverse();
}
// Step 2: Invert values
for(let i = 0; i < matrix.length; i++) {
for(let j = 0; j < matrix[i].length; j++) {
matrix[i][j] = matrix[i][j] === 1 ? 0 : 1;
}
}
return matrix;
};
console.log(flipAndInvertSeparate(arr2));
[ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 1, 1, 1 ] ]
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| In-Place Combined | O(m × n) | O(1) | Complex |
| Separate Operations | O(m × n) | O(1) | Simple |
Conclusion
Both methods achieve the same result with O(m × n) time complexity. The separate operations approach is more readable and easier to understand, while the combined approach is more optimized for performance.
