Click here to Skip to main content
14,579,188 members
Rate this:
Please Sign up or sign in to vote.
See more:
Ques:1
Hitain is a very naughty boy in CSE Batch. One day he was playing with strings, and randomly shuffled them all. Your task is to help Hitain Sort all the strings (lexicographically) but if a string is present completely as a prefix in another string, then string with longer length should come first. Eg Cat, Catwoman are 2 strings and the string cat is present as a prefix in Catwoman - then sorted order should have - Catwoman, cat.
Constraints
N<1000
Output Format
N lines each containing one string.
Sample Input
3
cat
apple
catwoman
Sample Output

apple
catwoman
cat
bat
&l

What I have tried:

n = int(input())
arr=[]
for i in range(n):
    temp=input()
    arr.append(temp)
arr.sort(key=len, reverse=True)
for i in range(1, len(arr)-1):
    key1=arr[i]
    key = arr[i][:len(arr[i+1])]
    j = i-1
    while j >=0 and key < arr[j] : 
        arr[j+1] = arr[j] 
        j -= 1
    arr[j+1] = key1 
for i in range(len(arr)):
    print(arr[i])
Posted
Comments
Richard MacCutchan 30-Jun-20 9:03am
   
I don't know where the bat came from. Maybe you should close the window.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100