Given two arrays of strings, words1 and words2, return True if every string in words1 is also present in words2, and False otherwise.
The solution must be optimized for massive datasets where each array can contain up to 1 million strings. A brute-force approach comparing each pair of strings will not be efficient enough.
Function Signature
def all_words_present(words1: list[str], words2: list[str]) -> bool:
...
Rules
-
Only presence matters. A string that appears several times in
words1
needs to appear only once in
words2
.
-
Strings in
words2
that are not in
words1
do not affect the answer.
-
Two strings match only when they are identical.
Constraints
-
1 <= len(words1), len(words2) <= 10^6
-
1 <= len(words1[i]), len(words2[j]) <= 100
-
Every string consists of lowercase English letters.
Examples
Input: words1 = ["apple", "banana", "cherry"], words2 = ["banana", "cherry", "date", "apple", "fig"]
Output: True
"apple", "banana" and "cherry" all appear in words2, so the result is True.
Input: words1 = ["apple", "banana", "grape"], words2 = ["banana", "cherry", "date", "apple", "fig"]
Output: False
"grape" from words1 is not present in words2, so the result is False.
Input: words1 = ["fig", "fig"], words2 = ["fig", "date"]
Output: True
"fig" appears twice in words1 and once in words2. Only presence counts, so one copy is enough.