LeetCode, 𝐃𝐚𝐲-11/365-DSA-Coding 𝐉𝐨𝐮𝐫𝐧𝐞𝐲…Google Prep…

Aaqib Ali
2 min readJan 10, 2025

--

Today I Learned: Problem — Word Subsets (#916)

The Word Subsets problem requires identifying all words in words1 that are universal with respect to words2. A word is universal if it contains all characters of every word in words2, respecting their frequencies.

Approach to Solve This Problem:

  1. Frequency Counter Construction:
  • I used Python’s Counter to create a frequency map (req) that records the maximum frequency of each character across all words in words2.

2. Validation of Words in words1:

  • For each word in words1, I counted its characters and checked if it meets or exceeds the required frequencies from req.
  • Words passing this condition were added to the result list.

Python Solution:

class Solution:
def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:
from collections import Counter

req = Counter()
for word in words2:
cur = Counter(word)
for ch in cur:
req[ch] = max(req[ch], cur[ch])

ans = []
for word in words1:
cur = Counter(word)
if all(cur[ch] >= req[ch] for ch in req):
ans.append(word)

return ans

Other Possible Approaches:

  • Bitmasking (for lowercase letters): Encode each word as a bitmask to compare character presence efficiently (limited by frequency handling).
  • Trie Data Structure: Build a trie for words2 to speed up prefix-based checks (though less effective for frequency-specific problems).
  • Set Operations: Use sets for simpler comparisons when frequency is not required, though it doesn’t solve this problem directly.

Key Learnings:

  • Effective use of Python’s Counter for frequency-based problems.
  • Pre-processing data for optimized comparisons.
  • Understanding problem constraints to choose the right data structures.

Usage:

  • Search Engines: Filtering search suggestions based on required keywords.
  • Recommendation Systems: Matching products with user preferences.
  • Text Analysis: Identifying documents containing specific word patterns.

Thank you for reading this! If you want to discuss your approach, let’s connect. Special thanks to iCodeGuru for continuous support and guidance. Keep learning, sharing, smiling, living, loving, and coding!

--

--

No responses yet