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
Selected Reading
Flip and Invert Matrix in Python
A binary matrix contains only 0s and 1s. To flip and invert a matrix, we need to reverse each row and then flip each bit (0 becomes 1, 1 becomes 0). This operation is commonly used in image processing and computer graphics.
Given this input matrix ?
| 1 | 1 | 0 |
| 0 | 1 | 0 |
| 0 | 0 | 1 |
The output will be ?
| 1 | 0 | 0 |
| 1 | 0 | 1 |
| 0 | 1 | 1 |
Algorithm Steps
To solve this problem, follow these steps ?
- For each row in the matrix:
- Reverse the row
- Flip each bit (0 ? 1, 1 ? 0)
- Return the modified matrix
Method 1: Using In-Place Modification
This approach modifies the original matrix directly ?
def flip_and_invert_matrix(mat):
for row in mat:
# Reverse the row
row.reverse()
# Flip each bit
for i in range(len(row)):
row[i] = 1 - row[i] # Flip 0 to 1, 1 to 0
return mat
# Test the function
matrix = [[1, 1, 0], [0, 1, 0], [0, 0, 1]]
print("Original matrix:", matrix)
result = flip_and_invert_matrix(matrix)
print("Flipped and inverted:", result)
Original matrix: [[1, 1, 0], [0, 1, 0], [0, 0, 1]] Flipped and inverted: [[1, 0, 0], [1, 0, 1], [0, 1, 1]]
Method 2: Using List Comprehension
This approach creates a new matrix without modifying the original ?
def flip_and_invert_matrix_v2(mat):
return [[1 - val for val in reversed(row)] for row in mat]
# Test the function
matrix = [[1, 1, 0], [0, 1, 0], [0, 0, 1]]
print("Original matrix:", matrix)
result = flip_and_invert_matrix_v2(matrix)
print("Flipped and inverted:", result)
Original matrix: [[1, 1, 0], [0, 1, 0], [0, 0, 1]] Flipped and inverted: [[1, 0, 0], [1, 0, 1], [0, 1, 1]]
Method 3: Using XOR Operation
XOR with 1 efficiently flips binary values ?
def flip_and_invert_matrix_xor(mat):
for row in mat:
row.reverse()
for i in range(len(row)):
row[i] ^= 1 # XOR with 1 flips the bit
return mat
# Test the function
matrix = [[1, 1, 0], [0, 1, 0], [0, 0, 1]]
print("Original matrix:", matrix)
result = flip_and_invert_matrix_xor(matrix)
print("Flipped and inverted:", result)
Original matrix: [[1, 1, 0], [0, 1, 0], [0, 0, 1]] Flipped and inverted: [[1, 0, 0], [1, 0, 1], [0, 1, 1]]
Comparison
| Method | Time Complexity | Space Complexity | Modifies Original |
|---|---|---|---|
| In-place modification | O(m×n) | O(1) | Yes |
| List comprehension | O(m×n) | O(m×n) | No |
| XOR operation | O(m×n) | O(1) | Yes |
Conclusion
Use list comprehension for a clean, functional approach that preserves the original matrix. Use XOR operation for the most efficient bit flipping. All methods have O(m×n) time complexity where m is rows and n is columns.
Advertisements
