Substring Sort | Alternative code to sort substrings ; sort the input array ; repeated length should be the same string ; two different strings with the same length input array cannot be sorted ; validate that each string is a substring of the following one ; get first element ; The array is valid and sorted print the strings in order ; Test 1 ; Test 2
def substringSort ( arr , n , maxLen ) : NEW_LINE INDENT count = [ 0 ] * ( maxLen ) NEW_LINE sortedArr = [ " " ] * ( maxLen ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT s = arr [ i ] NEW_LINE Len = len ( s ) NEW_LINE if ( count [ Len - 1 ] == 0 ) : NEW_LINE INDENT sortedArr [ Len - 1 ] = s NEW_LINE count [ Len - 1 ] = 1 NEW_LINE DEDENT elif ( sortedArr [ Len - 1 ] == s ) : NEW_LINE INDENT count [ Len - 1 ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Cannot ▁ be ▁ sorted " ) NEW_LINE return NEW_LINE DEDENT DEDENT index = 0 NEW_LINE while ( count [ index ] == 0 ) : NEW_LINE INDENT index += 1 NEW_LINE DEDENT prev = index NEW_LINE prevString = sortedArr [ prev ] NEW_LINE index += 1 NEW_LINE while index < maxLen : NEW_LINE INDENT if ( count [ index ] != 0 ) : NEW_LINE INDENT current = sortedArr [ index ] NEW_LINE if ( prevString in current ) : NEW_LINE INDENT prev = index NEW_LINE prevString = current NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Cannot ▁ be ▁ sorted " ) NEW_LINE return NEW_LINE DEDENT DEDENT index += 1 NEW_LINE DEDENT for i in range ( maxLen ) : NEW_LINE INDENT s = sortedArr [ i ] NEW_LINE for j in range ( count [ i ] ) : NEW_LINE INDENT print ( s ) NEW_LINE DEDENT DEDENT DEDENT maxLen = 100 NEW_LINE arr1 = [ " d " , " zddsaaz " , " ds " , " ddsaa " , " dds " , " dds " ] NEW_LINE substringSort ( arr1 , len ( arr1 ) , maxLen ) NEW_LINE arr2 = [ " for " , " rof " ] NEW_LINE substringSort ( arr2 , len ( arr2 ) , maxLen ) NEW_LINE