Press "Enter" to skip to content

Posts tagged as “union”

花花酱 LeetCode 916. Word Subsets

Problem

We are given two arraysĀ AĀ andĀ BĀ of words.Ā  Each word is a string of lowercase letters.

Now, say thatĀ wordĀ bĀ is a subset of wordĀ aĀ if every letter inĀ bĀ occurs inĀ a,Ā including multiplicity.Ā  For example,Ā "wrr"Ā is a subset ofĀ "warrior", but is not a subset ofĀ "world".

Now say a wordĀ aĀ fromĀ AĀ isĀ universalĀ if for everyĀ bĀ inĀ B,Ā bĀ is a subset ofĀ a.

Return a list of all universal words inĀ A.Ā  You can return the words in any order.

Example 1:

Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["e","o"]
Output: ["facebook","google","leetcode"]

Example 2:

Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["l","e"]
Output: ["apple","google","leetcode"]

Example 3:

Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["e","oo"]
Output: ["facebook","google"]

Example 4:

Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["lo","eo"]
Output: ["google","leetcode"]

Example 5:

Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["ec","oc","ceo"]
Output: ["facebook","leetcode"]

Note:

  1. 1 <= A.length, B.length <= 10000
  2. 1 <= A[i].length, B[i].lengthĀ <= 10
  3. A[i]Ā andĀ B[i]Ā consist only of lowercase letters.
  4. All words inĀ A[i]Ā are unique: there isn’tĀ i != jĀ withĀ A[i] == A[j].

Solution: Hashtable

Find the max requirement for each letter from B.

Time complexity: O(|A|+|B|)

Space complexity: O(26)

C++