Problem 599

Abstract / Summary

Find the restaurant that appears in both lists and has the smallest sum of its positions in each list.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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] ]
5 lines | 301 bytes | submitted October 1, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (500k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.44 | σ = 1.10

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
40 links | 26 authors | 9 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

1 easy
2 solutions   October 1, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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