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
Check if Matrix remains unchanged after row reversals in Python
When working with matrices, sometimes we need to check if a matrix remains unchanged after reversing each row. This means checking if each row is a palindrome − reads the same forwards and backwards.
For example, if we have a matrix like:
| 6 | 8 | 6 |
| 2 | 8 | 2 |
| 3 | 3 | 3 |
After reversing each row, we get the same matrix, so the output will be True.
Algorithm
To solve this problem, we follow these steps:
- Get the number of rows in the matrix
- For each row, use two pointers (left and right)
- Compare elements from both ends moving towards the center
- If any pair doesn't match, return
False - If all rows are palindromes, return
True
Implementation
Here's the complete solution:
def solve(matrix):
n = len(matrix)
for i in range(n):
left = 0
right = n - 1
while left <= right:
if matrix[i][left] != matrix[i][right]:
return False
left += 1
right -= 1
return True
# Test with the example matrix
matrix = [
[6, 8, 6],
[2, 8, 2],
[3, 3, 3]
]
print(solve(matrix))
True
How It Works
The algorithm works by checking each row individually:
- Row 1: [6, 8, 6] − comparing 6==6 (ends), 8==8 (middle) ?
- Row 2: [2, 8, 2] − comparing 2==2 (ends), 8==8 (middle) ?
- Row 3: [3, 3, 3] − all elements are same ?
Since all rows are palindromes, the matrix remains unchanged after row reversals.
Additional Example
Let's test with a matrix that changes after row reversal:
# Matrix that is NOT unchanged after row reversal
matrix2 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(solve(matrix2))
False
Time and Space Complexity
- Time Complexity: O(n²) where n is the number of rows/columns
- Space Complexity: O(1) as we only use constant extra space
Conclusion
This solution efficiently checks if a matrix remains unchanged after row reversals by verifying that each row is a palindrome. The two-pointer approach ensures optimal time complexity while using minimal extra space.
