Minimum Index Sum for Common Elements of Two Lists | Hashing based Java 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 ; Driver code ; Creating list1 ; Creating list2
import java . util . * ; class GFG { static void find ( Vector < String > list1 , Vector < String > list2 ) { Map < String , Integer > map = new HashMap < > ( ) ; for ( int i = 0 ; i < list1 . size ( ) ; i ++ ) map . put ( list1 . get ( i ) , i ) ; Vector < String > res = new Vector < String > ( ) ; int minsum = Integer . MAX_VALUE ; for ( int j = 0 ; j < list2 . size ( ) ; j ++ ) { if ( map . containsKey ( list2 . get ( j ) ) ) { int sum = j + map . get ( list2 . get ( j ) ) ; if ( sum < minsum ) { minsum = sum ; res . clear ( ) ; res . add ( list2 . get ( j ) ) ; } else if ( sum == minsum ) res . add ( list2 . get ( j ) ) ; } } for ( int i = 0 ; i < res . size ( ) ; i ++ ) System . out . print ( res . get ( i ) + " ▁ " ) ; } public static void main ( String [ ] args ) { Vector < String > list1 = new Vector < String > ( ) ; list1 . add ( " GeeksforGeeks " ) ; list1 . add ( " Udemy " ) ; list1 . add ( " Coursera " ) ; list1 . add ( " edX " ) ; Vector < String > list2 = new Vector < String > ( ) ; list2 . add ( " Codecademy " ) ; list2 . add ( " Khan ▁ Academy " ) ; list2 . add ( " GeeksforGeeks " ) ; find ( list1 , list2 ) ; } }