- Related Questions & Answers
- Minimum Index Sum for Common Elements of Two Lists in C++
- Find minimum of each index in list of lists in Python
- Minimum ASCII Delete Sum for Two Strings in C++
- Minimum sum of two numbers formed from digits of an array in C++
- Minimum sum path between two leaves of a binary trees in C++
- Intersect two lists in C#
- Program to find minimum difference between two elements from two lists in Python
- Minimum Path Sum in C++
- C# program to find Intersection of two lists
- Find sum of even index binomial coefficients in C++
- How to join two lists in C#?
- Find minimum sum of factors of number using C++.
- Intersection of Two Linked Lists in Python
- Minimum Size Subarray Sum in C++
- Minimum Falling Path Sum in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

Let us see the following implementation to get better understanding −

#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)); }

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

[ABC, ]

Advertisements