Find the longest string that can be made up of other strings from the array | Function that returns true if string s can be made up of by other two string from the array after concatenating one after another ; If current string has been processed before ; If current string is found in the map and it is not the string under consideration ; Split the string into two contiguous sub - strings ; If left sub - string is found in the map and the right sub - string can be made from the strings from the given array ; If everything failed , we return false ; Function to return the longest string that can made be made up from the other string of the given array ; Put all the strings in the map ; Sort the string in decreasing order of their lengths ; Starting from the longest string ; If current string can be made up from other strings ; Driver code
def canbuildword ( s , isoriginalword , mp ) : NEW_LINE INDENT if s in mp and mp [ s ] == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT if s in mp and mp [ s ] == 1 and isoriginalword == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT left = s [ : i ] NEW_LINE right = s [ i : ] NEW_LINE if left in mp and mp [ left ] == 1 and canbuildword ( right , 0 , mp ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT mp [ s ] = 0 NEW_LINE return False NEW_LINE DEDENT def printlongestword ( listofwords ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in listofwords : NEW_LINE INDENT mp [ i ] = 1 NEW_LINE DEDENT listofwords . sort ( key = lambda x : len ( x ) , reverse = True ) NEW_LINE for i in listofwords : NEW_LINE INDENT if canbuildword ( i , 1 , mp ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return " - 1" NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT listofwords = [ " geeks " , " for " , " geeksfor " , " geeksforgeeks " ] NEW_LINE print ( printlongestword ( listofwords ) ) NEW_LINE DEDENT