LeetCode Solutions

916. Word Subsets

Time:

Space:

			

class Solution {
 public:
  vector<string> wordSubsets(vector<string>& A, vector<string>& B) {
    vector<string> ans;
    vector<int> countB(26);

    for (const string& b : B) {
      vector<int> temp = counter(b);
      for (int i = 0; i < 26; ++i)
        countB[i] = max(countB[i], temp[i]);
    }

    for (const string& a : A)
      if (isUniversal(counter(a), countB))
        ans.push_back(a);

    return ans;
  }

 private:
  vector<int> counter(const string& s) {
    vector<int> count(26);
    for (char c : s)
      ++count[c - 'a'];
    return count;
  }

  bool isUniversal(vector<int> countA, vector<int>& countB) {
    for (int i = 0; i < 26; ++i)
      if (countA[i] < countB[i])
        return false;
    return true;
  }
};
			

class Solution {
  public List<String> wordSubsets(String[] A, String[] B) {
    List<String> ans = new ArrayList<>();
    int[] countB = new int[26];

    for (final String b : B) {
      int[] temp = counter(b);
      for (int i = 0; i < 26; ++i)
        countB[i] = Math.max(countB[i], temp[i]);
    }

    for (final String a : A)
      if (isUniversal(counter(a), countB))
        ans.add(a);

    return ans;
  }

  private int[] counter(final String s) {
    int[] count = new int[26];
    for (char c : s.toCharArray())
      ++count[c - 'a'];
    return count;
  }

  private boolean isUniversal(int[] countA, int[] countB) {
    for (int i = 0; i < 26; ++i)
      if (countA[i] < countB[i])
        return false;
    return true;
  }
}
			

class Solution:
  def wordSubsets(self, A: List[str], B: List[str]) -> List[str]:
    count = Counter()

    for b in B:
      count = count | Counter(b)

    return [a for a in A if Counter(a) & count == count]