#599

Minimum Index Sum of Two Lists

Easy
ArrayHash TableStringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a HashMap allows us to store the indices of strings in list1, making it easy to find common strings and their index sums in a single pass through list2.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a HashMap to store the strings from list1 with their indices.
  2. 2Step 2: Initialize variables to track the minimum index sum and a list for common strings.
  3. 3Step 3: Iterate through list2, checking if each string exists in the HashMap. If it does, calculate the index sum.
  4. 4Step 4: Update the list of common strings based on the minimum index sum found.
solution.py13 lines
1def findRestaurant(list1, list2):
2    index_map = {s: i for i, s in enumerate(list1)}
3    common = []
4    min_sum = float('inf')
5    for j, s in enumerate(list2):
6        if s in index_map:
7            index_sum = index_map[s] + j
8            if index_sum < min_sum:
9                min_sum = index_sum
10                common = [s]
11            elif index_sum == min_sum:
12                common.append(s)
13    return common

Complexity note: The time complexity is O(n) because we make a single pass through list1 to build the HashMap and another pass through list2 to find common strings. The space complexity is O(n) due to the HashMap storing the strings from list1.

  • 1Using a HashMap significantly reduces the time complexity.
  • 2Finding common elements can be optimized by storing indices.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.