
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.