- Insert the characters of the string into a square matrix A of dimensions √L x √L in row-wise manner.
- Initialize another matrix M with 0s. Fill the left diagonal with 1. Now, for 1 present in the left diagonal, fill its corresponding right diagonal with 1s.
- Now, check if all the indices in matrix M which contains 1, contains the same character in A.
If the condition is satisfied, print “Yes”. Otherwise, print “No”.
Input: S = ”abacdaeaafaghaia”
Input: S = ”abacdaeabfaghaia”
Approach: The idea is to traverse the matrix A where its corresponding character in the matrix M is 1. Follow the steps below to solve the problem:
- Calculate the dimensions of the matrix as N = √L.
- Iterate over the left diagonal by visiting each cell, A[i][i] where 1<= i<= N.
- For every element of the left diagonal at cell A[i][i], initialize variables x and y with i and traverse its corresponding right diagonal by visiting the character S[x*N + y] and S[y*N + x] and decrement x each time by 1 and increment y each time by 1 to move along the next cells in the right diagonals, while x is not smaller than 0 and y is smaller than N.
- If all characters are found to be same in the above step, print “Yes”. Otherwise, print “No” if any mismatch is found.
Below is the implementation of the above approach:
Time Complexity: O(L) where L is the length of the given string.
Auxiliary Space: O(L)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.