Minimum Index Sum for Common Elements of Two Lists | Hashing based Python3 program to find common elements with minimum index sum ; Function to print common strings with minimum index sum ; Mapping strings to their indices ; Resultant list ; If current sum is smaller than minsum ; If index sum is same then put this string in resultant list as well ; Print result ; Creating list1 ; Creating list2
import sys NEW_LINE def find ( list1 , list2 ) : NEW_LINE INDENT Map = { } NEW_LINE for i in range ( len ( list1 ) ) : NEW_LINE INDENT Map [ list1 [ i ] ] = i NEW_LINE DEDENT res = [ ] NEW_LINE minsum = sys . maxsize NEW_LINE for j in range ( len ( list2 ) ) : NEW_LINE INDENT if list2 [ j ] in Map : NEW_LINE INDENT Sum = j + Map [ list2 [ j ] ] NEW_LINE if ( Sum < minsum ) : NEW_LINE INDENT minsum = Sum NEW_LINE res . clear ( ) NEW_LINE res . append ( list2 [ j ] ) NEW_LINE DEDENT elif ( Sum == minsum ) : NEW_LINE INDENT res . append ( list2 [ j ] ) NEW_LINE DEDENT DEDENT DEDENT print ( * res , sep = " ▁ " ) NEW_LINE 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