Python 0599.py
class Solution:
def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
dict1 = { w : i for i, w in enumerate(list1) }
both = sorted([ (i + dict1[w], w) for i, w in enumerate(list2) if w in dict1 ])
return [ w for i, w in both if i == both[0][0] ]
Difficulty
and has an acceptance rate of about 60% (500k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The findRestaurant method receives two lists of strings, each representing a set of restaurant names. Its purpose is to return all restaurant names that appear in both input lists and have the smallest possible sum of their indices (the position in each list). The implementation builds an index map for the first list, extracts the common elements together with their combined index, sorts them, and finally returns the names that share the minimal combined index.
Key Steps
Building an index map for the first list
dict1 = { w : i for i, w in enumerate(list1) }
A dictionary comprehension iterates over list1 with enumerate, storing each restaurant name w as a key and its index i as the value. This structure enables constant-time lookup of a restaurant’s position in the first list.
Filtering common restaurants and computing combined indices
both = sorted([ (i + dict1[w], w) for i, w in enumerate(list2) if w in dict1 ])
A list comprehension walks through list2. For each element w that also exists in dict1, it calculates the sum of the current index i (from list2) and the stored index dict1[w] (from list1). The resulting tuple (combined_index, w) is collected for every common restaurant. The sorted call orders these tuples by the combined index, placing the smallest sums first.
Selecting the restaurants with the minimal combined index
return [ w for i, w in both if i == both[0][0] ]
A final list comprehension iterates over the sorted both list. It extracts the restaurant name w for each tuple whose combined index i matches the first tuple’s index (both[0][0]). Because the list is sorted, both[0][0] represents the minimal combined index, and all entries sharing that value are returned.
Edge Cases Handled
The code naturally accommodates situations where the two input lists contain different lengths; the enumeration of list2 proceeds independently of list1. When a restaurant appears multiple times in list1, the dictionary retains the last occurrence’s index, ensuring a deterministic combined index for that name. If several restaurants share the same minimal index sum, the final comprehension gathers all of them, preserving the requirement to return every optimal match. The use of the if w in dict1 guard guarantees that only truly common entries are processed, avoiding accidental inclusion of non-matching items.
Performance Optimizations
Creating dict1 provides O(1) access to the index of any restaurant from the first list, eliminating the need for repeated linear scans. The list comprehension that builds both filters and computes combined indices in a single pass over list2, avoiding separate loops. Sorting is applied only to the subset of restaurants that appear in both lists, which can be considerably smaller than the original inputs, reducing the amount of work compared with sorting the entire cross-product. Finally, the selection of minimal-index restaurants leverages the already sorted order, allowing a simple equality check against the first element’s index rather than scanning for a minimum value.
ELI5 - Simplified Explanation
Imagine there are two lists of favorite restaurants written on pieces of paper. The goal is to figure out which places appear on both lists and pick the ones that are closest to the top of both lists combined.
First, the code takes the first list and turns it into a map. Think of this like labeling each restaurant with a number to show exactly which spot it occupies in line. The first place gets a zero, the second gets a one, and so on.
Next, the code looks at the second list and checks every restaurant one by one. If a restaurant from the second list is also on the first list, the code adds the two numbers together. This total number represents the rank of the restaurant across both lists. A smaller number means the restaurant is a favorite in both places.
After checking all the common restaurants, the code sorts them by their total scores so the ones with the smallest numbers come first. Finally, it picks out the restaurant names that have the absolute smallest score and puts them into a new list for you to see.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Python | Rust | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| Dijkstra-Edu | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fengvyi | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| Krazune | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| Dijkstra-Edu | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fengvyi | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| Krazune | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 160: Intersection of Two Linked Lists
Solved On The Same Day
- problem 766: Toeplitz Matrix
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality