Given two unsorted lists of strings, words1 and words2, return every string that appears in both lists. Each common string appears in the result only once, even if it occurs several times in either list.
A naive approach compares every element in words1 against every element in words2, which is O(N2) when both lists hold about N strings. Your task is to bring this down to O(N) or O(NlogN).
Function Signature
def find_common_words(words1: list[str], words2: list[str]) -> list[str]:
...
Rules
-
Return the common strings sorted in ascending lexicographic order (Python's default string ordering), so the expected output is unique.
-
Each string in the result appears exactly once.
-
If no string appears in both lists, return an empty list.
Constraints
-
1 <= len(words1), len(words2) <= 10^5
-
1 <= len(words1[i]), len(words2[j]) <= 100
-
Every string consists of lowercase English letters.
Examples
Input: words1 = ["apple", "banana", "cherry", "date"], words2 = ["banana", "date", "fig", "grape"]
Output: ["banana", "date"]
"banana" and "date" are the only strings found in both lists, and they are already in alphabetical order.
Input: words1 = ["hello", "world", "hello", "foo"], words2 = ["foo", "bar", "hello", "hello"]
Output: ["foo", "hello"]
"foo" and "hello" appear in each list. "hello" occurs twice in both lists but is listed once, and "foo" comes first alphabetically.
Input: words1 = ["cat", "dog"], words2 = ["bird", "fish"]
Output: []
The lists share no string, so the result is empty.