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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void find ( vector < string > list1 , vector < string > list2 ) { unordered_map < string , int > map ; for ( int i = 0 ; i < list1 . size ( ) ; i ++ ) map [ list1 [ i ] ] = i ; vector < string > res ; int minsum = INT_MAX ; for ( int j = 0 ; j < list2 . size ( ) ; j ++ ) { if ( map . count ( list2 [ j ] ) ) { int sum = j + map [ list2 [ j ] ] ; if ( sum < minsum ) { minsum = sum ; res . clear ( ) ; res . push_back ( list2 [ j ] ) ; } else if ( sum == minsum ) res . push_back ( list2 [ j ] ) ; } } for ( int i = 0 ; i < res . size ( ) ; i ++ ) cout << res [ i ] << " ▁ " ; } int main ( ) { vector < string > list1 ; list1 . push_back ( " GeeksforGeeks " ) ; list1 . push_back ( " Udemy " ) ; list1 . push_back ( " Coursera " ) ; list1 . push_back ( " edX " ) ; vector < string > list2 ; list2 . push_back ( " Codecademy " ) ; list2 . push_back ( " Khan ▁ Academy " ) ; list2 . push_back ( " GeeksforGeeks " ) ; find ( list1 , list2 ) ; return 0 ; }