File: minimum-index-sum-of-two-lists/solution.py

Date: 2026-06-06

Time: 17:58

Purpose

This file solves LeetCode 599 — Minimum Index Sum of Two Lists. Given two lists of restaurant names (unique strings), find the common restaurants where the sum of their indices across both lists is minimized. If multiple restaurants share the same minimum index sum, return all of them.

The file is self-contained: it defines the solution function and its unit tests in a single module, following the project-wide convention across leetcode-implementations/.

Key Components

findRestaurant(list1, list2) -> list[str]

The sole exported function. Contract:

TestFindRestaurant

Seven test cases covering: single match, multiple matches with different sums, ties, single-element lists, full overlap, and early termination.

Patterns

Index map + single-pass scan: The function builds a hash map from list1 (string → index), then scans list2 once. This avoids an O(n*m) brute-force comparison.

Early termination optimization (line 20–21): if j > minsum: break. Once the list2 index alone exceeds the current best sum, no future element can improve the answer — because indexmap[s] is non-negative, so indexmap[s] + j >= j > minsum. This prunes the tail of list2 without examining it.

Greedy result replacement (lines 22–26): When a strictly better sum is found, the result list is replaced entirely (result = [s]). Ties append. This avoids a second pass to filter.

Dependencies

Imports: Only unittest from the standard library. No external dependencies.

Imported by: The "Imported By" list in the prompt is misleading — it reflects a project-wide cross-reference of test files that import unittest, not files that actually import this module. The real consumer is minimum-index-sum-of-two-lists/test_solution.py.

Flow

1. Build index map: Enumerate list1, storing {string: index} in index_map. O(n).

2. Scan list2: For each (j, s) in list2:

3. Return the accumulated result list.

Invariants

Error Handling

None. The function trusts its inputs per the LeetCode contract. No validation on empty lists, type checking, or bounds enforcement. If both lists are empty, the function returns [] naturally.

Topics to Explore

Beliefs