You get two lists of strings, list1 and list2. Neither list repeats a string, and at least one string shows up in both.
For a string that is in both lists, at position i in list1 and position j in list2, its index sum is i + j. Return every shared string whose index sum is the smallest possible, in any order.
Example 1
Input: list1 = ["red", "blue", "green", "pink"],
list2 = ["pink", "green", "gray"]
Output: ["pink", "green"]
Why: pink is 3 + 0 and green is 2 + 1; both sum to 32 more examples and the constraints
Example 2
Input: list1 = ["cab", "bus", "car"], list2 = ["car", "cab"] Output: ["cab"] Why: cab sums to 0 + 1 = 1, car to 2 + 0 = 2
Example 3
Input: list1 = ["x"], list2 = ["x"] Output: ["x"] Why: the only shared string, with sum 0
Constraints
- 1 ≤ length of list1, length of list2 ≤ 1,000
- Each string has 1 to 30 characters: English letters and spaces
- Strings within one list are distinct, and the lists share at least one string
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Compare every pairO(n·m)
- Index mapO(n + m)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for two lists of 1,000 strings | Verdict |
|---|---|---|---|
| Compare every pair | O(n·m) | Fine for small lists only | |
| Index map | O(n + m) | Best; one lookup per string |
n = length of list1, m = length of list2, L = string length.
Edge cases to test
- A tie. Example 1 returns two strings with the same sum; keep both, not just the first.
- A later, smaller sum. If a new string beats best, throw away everything collected so far.
- One string each. ["x"] and ["x"] give ["x"] with sum 0.
- Strings with spaces. "ice cream" is one string; compare whole strings, not words.
- Only one shared string, far down both lists. It is the answer whatever its sum.
Common mistakes
- Returning only the first string with the smallest sum, dropping ties.
- Forgetting to clear the result when a smaller sum turns up.
- Minimising i alone or j alone instead of i + j.
How to talk through it
- 1Clarify. Can strings repeat inside a list? Is there always a shared string? Does the answer order matter?
- 2Give the brute force. Compare every pair and track the smallest i + j: O(n·m).
- 3Name the lookup. The inner loop just finds a string's index in list1; a map does that in O(1).
- 4Code the scan. Build the map, walk list2, reset on a smaller sum and append on a tie.
- 5Test out loud. Run a tie and a case where a later string beats the first match.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?