Word Subsets - Problem

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 is not a subset of "world".

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

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

Input & Output

Example 1 — Basic Universal Check
$ Input: words1 = ["warrior","world"], words2 = ["w","o","r"]
Output: ["warrior","world"]
💡 Note: "warrior" contains w:2≥1, o:1≥1, r:3≥1. "world" contains w:1≥1, o:1≥1, r:1≥1. Both are universal.
Example 2 — Multiplicity Check
$ Input: words1 = ["warrior","world"], words2 = ["w","o","ld"]
Output: ["world"]
💡 Note: For "ld", need l:1, d:1. "warrior" has l:0, d:0. "world" has l:1≥1, d:1≥1. Only "world" is universal.
Example 3 — No Universal Words
$ Input: words1 = ["abc","def"], words2 = ["xyz"]
Output: []
💡 Note: Neither "abc" nor "def" contains x, y, or z. No words are universal.

Constraints

  • 1 ≤ words1.length, words2.length ≤ 104
  • 1 ≤ words1[i].length, words2[i].length ≤ 10
  • words1[i] and words2[i] consist only of lowercase English letters.

Visualization

Tap to expand
Word Subsets - Merge Requirements First INPUT words1[] "warrior" "world" words2[] "w" "o" "r" Subset Concept: "wrr" subset of "warrior" OK (w:1, r:2 satisfied) "wrr" NOT subset of "world" Find universal words that contain ALL words2 as subsets ALGORITHM STEPS 1 Merge words2 requirements Take max count per char "w"--> w:1 | "o"--> o:1 | "r"--> r:1 merged = {w:1, o:1, r:1} 2 Count chars in each word1 Build frequency map 3 Compare with merged Check if word satisfies all word counts result warrior w:1,a:1,r:2,i:1,o:1 OK world w:1,o:1,r:1,l:1,d:1 OK 4 Collect universal words Add to result if valid FINAL RESULT Universal Words Found: "warrior" "world" Both satisfy merged {w:1,o:1,r:1} Verification: "warrior" contains: w:1+ o:1+ r:1+ ... OK "world" contains: w:1+ o:1+ r:1+ ... OK Output: ["warrior", "world"] Key Insight: Instead of checking each word1 against ALL words2 (O(n*m)), merge words2 into one requirement map by taking the maximum count of each character. Then check each word1 only against this merged map. Time Complexity: O(n + m) where n = total chars in words1, m = total chars in words2 TutorialsPoint - Word Subsets | Optimized - Merge Requirements First
Asked in
Google 25 Facebook 18
31.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen