Skip to main content
Back to problems
#916
Medium Algorithms

Word subsets

Array Hash Table String
55.9% acceptance
Feb 25, 2026
3533
316
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn word_subsets(words1: Vec<String>, words2: Vec<String>) -> Vec<String> {
    let freq2 = words2.iter().fold([0u32; 26], |mut acc, w| {
      let mut f = [0u32; 26];
      for b in w.bytes() { f[(b - b'a') as usize] += 1; }
      for i in 0..26 { acc[i] = acc[i].max(f[i]); }
      acc
    });
    words1.into_iter().filter(|w| {
      let mut f = [0u32; 26];
      for b in w.bytes() { f[(b - b'a') as usize] += 1; }
      (0..26).all(|i| f[i] >= freq2[i])
    }).collect()
  }
}