Minimum Index Sum for Common Elements of Two Lists | Function to print common strings with minimum index sum ; resultant list ; iterating over sum in ascending order ; iterating over one list and check index ( Corresponding to given sum ) in other list ; put common strings in resultant list ; if common string found then break as we are considering index sums in increasing order . ; print the resultant list ; Creating list1 ; Creating list2
def find ( list1 , list2 ) : NEW_LINE INDENT res = [ ] NEW_LINE max_possible_sum = len ( list1 ) + len ( list2 ) - 2 NEW_LINE for sum in range ( max_possible_sum + 1 ) : NEW_LINE INDENT for i in range ( sum + 1 ) : NEW_LINE INDENT if ( i < len ( list1 ) and ( sum - i ) < len ( list2 ) and list1 [ i ] == list2 [ sum - i ] ) : NEW_LINE INDENT res . append ( list1 [ i ] ) NEW_LINE DEDENT DEDENT if ( len ( res ) > 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT for i in range ( len ( res ) ) : NEW_LINE INDENT print ( res [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT list1 = [ ] NEW_LINE list1 . append ( " GeeksforGeeks " ) NEW_LINE list1 . append ( " Udemy " ) NEW_LINE list1 . append ( " Coursera " ) NEW_LINE list1 . append ( " edX " ) NEW_LINE list2 = [ ] NEW_LINE list2 . append ( " Codecademy " ) NEW_LINE list2 . append ( " Khan ▁ Academy " ) NEW_LINE list2 . append ( " GeeksforGeeks " ) NEW_LINE find ( list1 , list2 ) NEW_LINE