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
function substringSort ( arr , n , maxLen ) { let count = new Array ( maxLen ) ; let sortedArr = new Array ( maxLen ) ; count . fill ( 0 ) ; for ( let i = 0 ; i < maxLen ; i ++ ) { sortedArr [ i ] = " " ; } for ( let i = 0 ; i < n ; i ++ ) { let s = arr [ i ] ; let len = s . length ; if ( count [ len - 1 ] == 0 ) { sortedArr [ len - 1 ] = s ; count [ len - 1 ] = 1 ; } else if ( sortedArr [ len - 1 ] == s ) { count [ len - 1 ] ++ ; } else { document . write ( " " + " " ) ; return ; } } let index = 0 ; while ( count [ index ] == 0 ) index ++ ; let prev = index ; let prevString = sortedArr [ prev ] ; index ++ ; for ( ; index < maxLen ; index ++ ) { if ( count [ index ] != 0 ) { let current = sortedArr [ index ] ; if ( current . includes ( prevString ) ) { prev = index ; prevString = current ; } else { document . write ( " " ) ; return ; } } } for ( let i = 0 ; i < maxLen ; i ++ ) { let s = sortedArr [ i ] ; for ( let j = 0 ; j < count [ i ] ; j ++ ) { document . write ( s + " " ) ; } } } let maxLen = 100 ; let arr1 = [ " " , " " , " " , " " , " " , " " ] ; substringSort ( arr1 , arr1 . length , maxLen ) ; let arr2 = [ " " , " " ] ; substringSort ( arr2 , arr2 . length , maxLen ) ;