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 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 list (or array) is a transformation where elements are shifted to the left (or right), and the element at the end will be wrapped 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: Then, append each element of the first row to the concat, with "-" before each element.
  • Step 3: Now, duplicate the concat by appending it to itself. This allows us to check for circular rotations.
  • Step 4: For every other row in the matrix, build the string curr_row for each 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 none of the rows match as a circular rotation, return False.

Example

Consider the following implementation to get a better understanding:

def solve(matrix):
   concat = ""
   for i in range(len(matrix[0])):
      concat = concat + "-" + str(matrix[0][i])
   concat = concat + concat
   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 concat.find(curr_row) != -1:
         return True
   return False
matrix = [['B', 'A', 'D', 'C'],
   ['C', 'B', 'A', 'D'],
   ['D', 'C', 'B', 'A'],
   ['A', 'D', 'C', 'B']]
print(solve(matrix))

Following is the output of the above program:

True

Conclusion

Checking if all rows of a matrix are circular rotations of each other is useful in array manipulation and string-matching logic. By doubling the base row and checking for sub-arrays, we can efficiently verify the rotations.

Updated on: 2025-07-30T16:38:27+05:30

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements