Word Subsets

You are given two string arrays `words1` and `words2`. A string `b` is a **subset** of string `a` if every letter in `b` occurs in `a`, **including multiplicity**. For example, `"wrr"` is a subset of `"warrior"` but not of `"world"`. A string `a` from `words1` is **universal** if every string `b` in `words2` is a subset of `a`. Return *an array of all the universal strings in* `words1`. You may return the answer in **any order**.

30:00

Word Subsets
medium
Free written solution
Topics
Companies

You are given two string arrays words1 and words2.

A string b is a subset of string a if every letter in b occurs in a, including multiplicity. For example, "wrr" is a subset of "warrior" but not of "world".

A string a from words1 is universal if every string b in words2 is a subset of a.

Return an array of all the universal strings in words1. You may return the answer in any order.

Example 1:
Input: {"words1":["amazon","apple","facebook","google","leetcode"],"words2":["e","o"]}
Output: ["facebook","google","leetcode"]
Constraints:
  • 1≤words1.length,words2.length≤1041 \leq \text{words1.length}, \text{words2.length} \leq 10^4

  • 1≤words1[i].length,words2[i].length≤101 \leq \text{words1}[i].\text{length}, \text{words2}[i].\text{length} \leq 10

  • words1[i] and words2[i] consist only of lowercase English letters.

  • All the strings of words1 are unique.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"words1":["amazon","apple","facebook","google","leetcode"],"words2":["e","o"]}

Checking every b against every a is slow. Instead, fold all of words2 into one requirement: for each letter, the most copies any single b needs.

words2: requirements

e
o

need[]

e

0

o

0

words1: candidates

amazon
apple
facebook
google
leetcode
required copies (need)
requirement met / universal
missing copy / rejected
word in focus
Variables
VariableValue
need-
kept0
DepthFunction Call
Stack empty
0/9