# Minimum Index Sum of Two Lists in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

Suppose there are two fiends Amal and Bimal want to choose a restaurant for dinner, now they both have a list of favorite restaurants represented by strings. We have to help them to find out their common interest with the least list index sum. If there is a choice tie between different answers, then return all of them with no order requirement.

So, if the input is like ["ABC","PQR","MNO","XYZ"], and ["TUV","GHI","KLM","ABC"], then the output will be ["ABC"]

To solve this, we will follow these steps −

• Define one map mp

• least := inf

• for initialize i := 0, when i < size of l1, update (increase i by 1), do −

• for initialize j := 0, when j < size of l2, update (increase j by 1), do −

• if l1[i] is same as l2[j], then −

• insert l1[i] at the end of mp[i + j]

• Define an array res

• it = first element of mp

• res := value of it

• return res

## Example

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
vector<string> findRestaurant(vector<string>& l1, vector<string>& l2) {
map<int, vector<string> > mp;
int least = INT_MAX;
for (int i = 0; i < l1.size(); i++)
for (int j = 0; j < l2.size(); j++)
if (l1[i] == l2[j])
mp[i + j].push_back(l1[i]);
vector<string> res;
auto it = mp.begin();
res = it->second;
return res;
}
};
main(){
Solution ob;
vector<string> v = {"ABC","PQR","MNO","XYZ"}, v1 = {"TUV","GHI","KLM","ABC"};
print_vector(ob.findRestaurant(v, v1));
}

## Input

{"ABC","PQR","MNO","XYZ"}, {"TUV","GHI","KLM","ABC"}

## Output

[ABC, ]
Updated on 11-Jun-2020 12:00:29