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 ; Driver code ; Creating list1 ; Creating list2
#include <bits/stdc++.h> NEW_LINE using namespace std ; void find ( vector < string > list1 , vector < string > list2 ) { vector < string > res ; int max_possible_sum = list1 . size ( ) + list2 . size ( ) - 2 ; for ( int sum = 0 ; sum <= max_possible_sum ; sum ++ ) { for ( int i = 0 ; i <= sum ; i ++ ) if ( i < list1 . size ( ) && ( sum - i ) < list2 . size ( ) && list1 [ i ] == list2 [ sum - i ] ) res . push_back ( list1 [ i ] ) ; if ( res . size ( ) > 0 ) break ; } 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 ; }