Minimum Index Sum for Common Elements of Two Lists | Hashing based C # 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
using System ; using System . Collections . Generic ; class GFG { static void find ( List < String > list1 , List < String > list2 ) { Dictionary < String , int > map = new Dictionary < String , int > ( ) ; for ( int i = 0 ; i < list1 . Count ; i ++ ) map . Add ( list1 [ i ] , i ) ; List < String > res = new List < String > ( ) ; int minsum = int . MaxValue ; for ( int j = 0 ; j < list2 . Count ; j ++ ) { if ( map . ContainsKey ( list2 [ j ] ) ) { int sum = j + map [ list2 [ j ] ] ; if ( sum < minsum ) { minsum = sum ; res . Clear ( ) ; res . Add ( list2 [ j ] ) ; } else if ( sum == minsum ) res . Add ( list2 [ j ] ) ; } } for ( int i = 0 ; i < res . Count ; i ++ ) Console . Write ( res [ i ] + " ▁ " ) ; } public static void Main ( String [ ] args ) { List < String > list1 = new List < String > ( ) ; list1 . Add ( " GeeksforGeeks " ) ; list1 . Add ( " Udemy " ) ; list1 . Add ( " Coursera " ) ; list1 . Add ( " edX " ) ; List < String > list2 = new List < String > ( ) ; list2 . Add ( " Codecademy " ) ; list2 . Add ( " Khan ▁ Academy " ) ; list2 . Add ( " GeeksforGeeks " ) ; find ( list1 , list2 ) ; } }