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:

  1. Row 1: [6, 8, 6] − comparing 6==6 (ends), 8==8 (middle) ?
  2. Row 2: [2, 8, 2] − comparing 2==2 (ends), 8==8 (middle) ?
  3. 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.

Updated on: 2026-03-25T15:18:12+05:30

139 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements