← Home

599. Minimum Index Sum of Two Lists

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
greedyC++Markdown
599

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 599. Minimum Index Sum of Two Lists, the solution in this repository is mainly a greedy solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: greedy.

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are sort_indexes, idx, findRestaurant.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
03
04You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.
05
06Example 1:
07Input:
08["Shogun", "Tapioca Express", "Burger King", "KFC"]
09["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
10Output: ["Shogun"]
11Explanation: The only restaurant they both like is "Shogun".
12Example 2:
13Input:
14["Shogun", "Tapioca Express", "Burger King", "KFC"]
15["KFC", "Shogun", "Burger King"]
16Output: ["Shogun"]
17Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1).
18Note:
19The length of both lists will be in the range of [1, 1000].
20The length of strings in both lists will be in the range of [1, 30].
21The index is starting from 0 to the list length minus 1.
22No duplicates in both lists.
23**/
24
25//Runtime: 152 ms, faster than 17.82% of C++ online submissions for Minimum Index Sum of Two Lists.
26//Memory Usage: 26.2 MB, less than 76.04% of C++ online submissions for Minimum Index Sum of Two Lists.
27
28class Solution {
29public:
30    template <typename T>
31    vector<size_t> sort_indexes(const vector<T> &v) {
32      // initialize original index locations
33      vector<size_t> idx(v.size());
34      iota(idx.begin(), idx.end(), 0);
35
36      // sort indexes based on comparing values in v
37      sort(idx.begin(), idx.end(),
38           [&v](size_t i1, size_t i2) {return v[i1].compare(v[i2]) < 0;});
39
40      return idx;
41    }
42    
43    vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
44        vector<size_t> ixs1 = sort_indexes(list1);
45        vector<size_t> ixs2 = sort_indexes(list2);
46        vector<string> ans;
47        
48        int cur1 = 0, cur2 = 0;
49        int lastIxSum = INT_MAX;
50        while(cur1 < list1.size() && cur2 < list2.size()){
51            size_t ix1 = ixs1[cur1];
52            size_t ix2 = ixs2[cur2];
53            string s1 = list1[ix1];
54            string s2 = list2[ix2];
55            
56            int comparision = s1.compare(s2);
57            if(comparision == 0){
58                cur1++;
59                cur2++;
60                // cout << s1 << endl;
61                // cout << ix1+ix2 << " " << lastIxSum << endl;
62                if(ix1 + ix2 < lastIxSum){
63                    ans.clear();
64                    ans.push_back(s1);
65                    lastIxSum = ix1 + ix2;
66                }else if(ix1 + ix2 == lastIxSum){
67                    ans.push_back(s1);
68                }
69            }else if(comparision < 0){
70                cur1++;
71            }else{
72                cur2++;
73            }
74        }
75        
76        return ans;
77    }
78};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.