Check if all rows of a matrix are circular rotations of each other in Python

Matrices are used to represent and manipulate structured data (such as grids, patterns). While working with matrix manipulation, we may find scenarios where we need to determine whether all the rows in a given matrix are circular rotations of one another.

Circular Rotation in a Matrix

A circular rotation of a row (or array) is a transformation where elements are shifted to the left (or right), and the element at the end wraps around to the beginning. For example, if the original row is [1, 2, 3], its circular rotations are ?

  • [2, 3, 1] (left-rotated once)
  • [3, 1, 2] (left-rotated twice)
  • and back to [1, 2, 3]

Algorithm to Solve the Problem

Let's look at the following algorithm ?

  • Step 1: Initialize an empty string concat
  • Step 2: Append each element of the first row to concat, with "-" as a separator
  • Step 3: Double the concat string by appending it to itself. This allows us to check for all circular rotations
  • Step 4: For every other row in the matrix, build the string curr_row in the same format as concat
  • Step 5: Check if curr_row exists in the doubled concat string
  • Step 6: If it does not exist, return False immediately (not a rotation)
  • Step 7: If all rows are found as rotations, return True

Method 1: Using String Concatenation and Search

This approach converts each row to a string and uses string search to find rotations ?

def check_circular_rotations(matrix):
    # Build string representation of first row
    concat = ""
    for i in range(len(matrix[0])):
        concat = concat + "-" + str(matrix[0][i])
    
    # Double the string to contain all rotations
    concat = concat + concat
    
    # Check each remaining row
    for i in range(1, len(matrix)):
        curr_row = ""
        for j in range(len(matrix[0])):
            curr_row = curr_row + "-" + str(matrix[i][j])
        
        # If current row is not found in doubled string, it's not a rotation
        if concat.find(curr_row) == -1:
            return False
    
    return True

# Test with a matrix where all rows are rotations
matrix = [['B', 'A', 'D', 'C'],
          ['C', 'B', 'A', 'D'],
          ['D', 'C', 'B', 'A'],
          ['A', 'D', 'C', 'B']]

print("Matrix 1 result:", check_circular_rotations(matrix))

# Test with a matrix where rows are NOT rotations
matrix2 = [['A', 'B', 'C'],
           ['B', 'C', 'A'],
           ['X', 'Y', 'Z']]

print("Matrix 2 result:", check_circular_rotations(matrix2))
Matrix 1 result: True
Matrix 2 result: False

Method 2: Using List Rotation Check

A more direct approach that generates all possible rotations and compares them ?

def is_rotation(row1, row2):
    """Check if row2 is a circular rotation of row1"""
    if len(row1) != len(row2):
        return False
    
    # Try all possible rotations
    for i in range(len(row1)):
        rotated = row1[i:] + row1[:i]
        if rotated == row2:
            return True
    return False

def check_rotations_method2(matrix):
    """Check if all rows are rotations of the first row"""
    if not matrix:
        return True
    
    first_row = matrix[0]
    
    for i in range(1, len(matrix)):
        if not is_rotation(first_row, matrix[i]):
            return False
    
    return True

# Test the method
matrix = [['B', 'A', 'D', 'C'],
          ['C', 'B', 'A', 'D'],
          ['D', 'C', 'B', 'A'],
          ['A', 'D', 'C', 'B']]

print("Result:", check_rotations_method2(matrix))
Result: True

Comparison

Method Time Complexity Space Complexity Best For
String Concatenation O(n × m) O(m) Simple implementation
List Rotation O(n × m²) O(m) Direct approach

Where n is the number of rows and m is the number of columns.

Conclusion

Checking if all rows of a matrix are circular rotations involves comparing each row with all possible rotations of the first row. The string concatenation method is more efficient, while the direct rotation method is more intuitive to understand.

Updated on: 2026-03-25T14:56:38+05:30

279 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements