Problem of the day
Ninja is coming after a long party to his home, but he faces a monster while returning. Monster puts up a condition to Ninja in order to free him. The monster gives him ‘n’ strings and asks him to sort them. However, he adds an extra condition to him.
Since the monster knows that Ninja could do it easily, the monster wants him to sort them using the last letter of each string. If there are strings with the same last character, sort them based on their second last character and so on.
Ninja gets totally confused, he asks you to solve the problem. Can you help Ninja figure out the correct order of strings?
The first line of input contains an integer ‘T,’ denoting the number of test cases. The test cases follow.
The first line of each test case contains a number ‘n’ denoting the number of strings.
The second line of each test case contains ‘n’ space-separated strings that the monster gave to Ninja.
Output Format:
For each test case, print the strings sorted according to the last character.
Print the output of each test case in a separate line.
Note:
You are not required to print the expected output; it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= n <= 10^3
1 <= size of string <= 10^2
Where 'T’ is the number of test cases, ‘n’ denotes the number of strings
Time Limit: 1 sec
2
5
abc abd aba xyb cdg
3
jog oop nop
aba xyb abc abd cdg
jog nop oop
In the first test case, the given strings are [“abc”,”abd”,”xyb”,”cdg”], the last character of strings are: ‘c’,’d’,’a’,’b’,’g’. So their sorted order is: ‘a’,’b’,’c’,’d’,’g’. Hence the sorted order of strings are:“aba”,”xyb”,”abc”,”abd”,”cdg”.
In the second test case, the given strings are [“jog”,”nop”,”oop”] the last characters of strings are: ‘g’,’p’,’p’.So their sorted order is : ‘g’,’p’,’p’. As we can see for strings “oop” and “nop”, their last character matches; we need to check from the second previous character till we find a mismatched character and sort them accordingly. Hence the sorted order of strings are: “jog”,” nop”,” oop”.
2
4
truck bus car auto
3
teacher student headmaster
truck auto car bus
teacher headmaster student
In the first test case, the given strings are [“truck”,”bus”,”car”,”auto”], the last character of strings are: ‘k’,’s’,’r’,’o’.So their sorted order is: ‘k’,’o’,’r’,’s’’. Hence the sorted order of strings are:“truck”,”auto”,”car”,”bus”.
In the second test case, the given strings are [“teacher”,”student”,”headmaster”] the last characters of strings are: ‘r’,’t’,’r’.So their sorted order is : ‘r’,’r’,’t’. As we can see for strings “teacher” and “headmaster”, their last character matches; we need to check from the second previous character till we find a mismatched character and sort them accordingly. Hence the sorted order of strings are: “teacher”,” headmaster”,”student”.