LeetCode 748: Shortest Completing Word Solution
Master LeetCode problem 748 (Shortest Completing Word), a easy 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.
748. Shortest Completing Word
Problem Explanation
Explanation
To solve this problem, we need to find the shortest word in the given list of words that contains all the letters in the license plate. We first create a frequency map of letters in the license plate and then iterate through each word in the list to check if it is a completing word. For each word, we create a frequency map and compare it with the license plate frequency map to determine if it contains all required letters. We then update the result with the shortest completing word found so far.
Algorithm:
- Create a frequency map for the letters in the license plate.
- Initialize a variable
resultto store the shortest completing word found so far. - Iterate through each word in the list of words:
- Create a frequency map for the letters in the current word.
- Check if the current word is a completing word by comparing its frequency map with the license plate frequency map.
- If it is a completing word and shorter than the current result, update the result.
- Return the result as the shortest completing word.
Time complexity: O(n * m), where n is the number of words and m is the length of the longest word. Space complexity: O(1) since the frequency maps have a fixed size.
Solution Code
class Solution {
public String shortestCompletingWord(String licensePlate, String[] words) {
int[] lpFreq = new int[26];
for (char c : licensePlate.toLowerCase().toCharArray()) {
if (Character.isLetter(c)) {
lpFreq[c - 'a']++;
}
}
String result = "";
for (String word : words) {
if (word.length() >= result.length() && (result.isEmpty() || word.length() < result.length())) {
int[] wordFreq = new int[26];
for (char c : word.toCharArray()) {
wordFreq[c - 'a']++;
}
boolean isCompleting = true;
for (int i = 0; i < 26; i++) {
if (lpFreq[i] > wordFreq[i]) {
isCompleting = false;
break;
}
}
if (isCompleting) {
result = word;
}
}
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 748 (Shortest Completing Word)?
This page provides optimized solutions for LeetCode problem 748 (Shortest Completing Word) 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 748 (Shortest Completing Word)?
The time complexity for LeetCode 748 (Shortest Completing Word) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 748 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 748 in Java, C++, or Python.