Largest Square Matrix – Words: The program must accept a string S containing multiple words as the input. The program must form a largest possible square matrix of size N*N based on the following conditions.
– The words of equal length must be used to form the square matrix (i.e., each row in the matrix contains all the characters of a word).
– The words in the given string must be used in the order of their occurrence.
Finally, the program must print the largest possible square matrix as the output. If there are two or more such largest square matrices, the program must print the matrix with the first N words of length N as the output. If it is not possible to form such a matrix, the program must print -1 as the output.
Boundary Condition(s):
1 <= Length of S <= 1000
Input Format:
The first line contains S.
Output Format:
The lines contain the largest possible square matrix or the first line contains -1.
Example Input/Output 1:
Input:
book planet MOON earth satellite stars rocket lava Aeroplane Fuel radar
Output:
b o o k
M O O N
l a v a
F u e l
Explanation:
The 4 letter words are book, MOON, lava and Fuel. These words can form a 4×4 square matrix.
The 5 letter words are earth, stars and radar. These words cannot form a square matrix.
The 6 letter words are planet and rocket. These words cannot form a square matrix.
The 9 letter words are satellite and Aeroplane. These words cannot form a square matrix.
Hence the output is
b o o k
M O O N
l a v a
F u e l
Example Input/Output 2:
Input:
an the were care one
Output:
-1
Example Input/Output 3:
Input:
I like mangoes
Output:
I
Example Input/Output 4:
Input:
12 apples 35 grapes 10 tables 40 chairs
Output:
1 2
3 5
s = input().strip().split()
d = dict()
for i in s:
try:
if len(d[len(i)]) < len(i):
d[len(i)].append(i)
except:
d[len(i)] = [i]
c = 0
for i in sorted(d)[::-1]:
if len(d[i]) == i:
for j in d[i]:
print(*list(j))
c = 1
break
if not c:
print(-1)
Leave a Reply