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: Find Universal Wordswords1 (candidates):"warrior""world"words2 (requirements):"w""o""r"Check: Does each word1 contain ALL characters from words2?"warrior": w✓ o✓ r✓"world": w✓ o✓ r✓Result: ["warrior", "world"]Both words are universal - they contain all required characters
Understanding the Visualization
1
Input Arrays
words1 candidates and words2 requirements
2
Subset Check
Verify each word1 contains all characters from all words2
3
Universal Words
Return words that satisfy all requirements
Key Takeaway
🎯 Key Insight: Merge all requirements first to avoid redundant character frequency checks
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