LeetCode 916: Word Subsets Solution
Master LeetCode problem 916 (Word Subsets), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
916. Word Subsets
Problem Explanation
Explanation
To solve this problem, we need to find the universal strings from words1 which contain all the letters present in any word in words2. We can achieve this by first finding the counts of each letter in all words in words2, then finding the maximum count of each letter across all words2 words. Finally, we iterate over words1 and check if each word contains all the letters with counts greater than or equal to the max counts found in words2.
Algorithm:
- Create a frequency array for each letter in all words in
words2. - Find the maximum count of each letter across all
words2words. - Iterate over
words1, for each word:- Create a frequency array for the current word.
- Check if the current word contains all the letters with counts greater than or equal to the max counts found in
words2. - If yes, add the word to the result list.
Time Complexity
The time complexity of this solution is O(n + m), where n is the total number of characters in words1 and words2, and m is the total number of unique characters in words2.
Space Complexity
The space complexity of this solution is O(1) since the frequency arrays have a constant size of 26 for lowercase English letters.
Solution Code
class Solution {
public List<String> wordSubsets(String[] words1, String[] words2) {
List<String> result = new ArrayList<>();
int[] maxFreq = new int[26];
for (String word : words2) {
int[] freq = new int[26];
for (char c : word.toCharArray()) {
freq[c - 'a']++;
}
for (int i = 0; i < 26; i++) {
maxFreq[i] = Math.max(maxFreq[i], freq[i]);
}
}
for (String word : words1) {
int[] freq = new int[26];
for (char c : word.toCharArray()) {
freq[c - 'a']++;
}
boolean isUniversal = true;
for (int i = 0; i < 26; i++) {
if (freq[i] < maxFreq[i]) {
isUniversal = false;
break;
}
}
if (isUniversal) {
result.add(word);
}
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 916 (Word Subsets)?
This page provides optimized solutions for LeetCode problem 916 (Word Subsets) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 916 (Word Subsets)?
The time complexity for LeetCode 916 (Word Subsets) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 916 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 916 in Java, C++, or Python.