Matrix: Given a matrix, check if all rows of a matrix are circular rotation of each other

Problem Statement:

You are given a 2D matrix of n*n size.

You need to find if all rows are circular rotation of each other.

Example:

Input:

1, 2, 3
3, 1, 2
2, 3, 1

Output: Yes

Solution Explanation:

Solution is very simple.

Take the first row and then create a string of the first row elements.

Then goto the next row and check if the current row string is a substring of the first row string.

If it is not, return false, else return true at the end of the program.

Time Complexity: O(n3)
Space Complexity: O(n)

Code Solution

#include <iostream>
using namespace std;

const int MAX = 100;

bool solution( int mat[MAX][MAX], int n)
{

    string concat = "";
    for (int i = 0 ; i < n ; i++)
        concat = concat + "-" + to_string(mat[0][i]);

    concat = concat + concat;

    for (int i=1; i<n; i++)
    {
        string curr_str = "";

        for (int j = 0 ; j < n ; j++)
            curr_str = curr_str + "-" + to_string(mat[i][j]);

        if (concat.find(curr_str) == string::npos)
            return false;
    }

    return true;
}

int main()
{
    int n = 3 ;

    int mat[MAX][MAX] = {
    		{1, 2, 3},
			{3, 1, 2},
			{2, 3, 1}};

    solution(mat, n)? cout << "Yes" :
                              cout << "No";
    return 0;
}

Output

Yes
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *