Leetcode 748. Shortest Completing Word
Given a string licensePlate and an array of strings words, find the shortest completing word in words. A completing word is a word that contains all the letters in the licensePlate (case insensitive). The letters in the licensePlate can be both uppercase and lowercase letters. Ignore numbers and spaces in the licensePlate. Return the shortest completing word in words. If there are multiple shortest completing words, return the first one that appears in words.
licensePlate contain special characters?
words array constrained?
licensePlate and the array words?
licensePlate and the words array will be within a range suitable for typical coding interview problems.To solve this problem, we can follow these steps:
licensePlate, ignoring non-letter characters.words, check if it can be a completing word.#include <string>
#include <vector>
#include <cctype>
#include <unordered_map>
#include <algorithm>
using namespace std;
string shortestCompletingWord(string licensePlate, vector<string>& words) {
unordered_map<char, int> charCount;
// Helper lambda function to convert character to lowercase and check if it's a letter
auto adjustAndCount = [&](char ch) {
if (isalpha(ch)) {
charCount[tolower(ch)]++;
}
};
// Count frequencies of each letter in the licensePlate
for (char ch : licensePlate) {
adjustAndCount(ch);
}
string result;
size_t minLen = numeric_limits<size_t>::max();
for (const string& word : words) {
unordered_map<char, int> wordCount;
for (char ch : word) {
wordCount[tolower(ch)]++;
}
bool isCompleting = true;
for (const auto& pair : charCount) {
if (wordCount[pair.first] < pair.second) {
isCompleting = false;
break;
}
}
if (isCompleting && word.length() < minLen) {
result = word;
minLen = word.length();
}
}
return result;
}
int main() {
string licensePlate = "1s3 PSt";
vector<string> words = {"step", "steps", "stripe", "stepple"};
string result = shortestCompletingWord(licensePlate, words);
cout << "Shortest completing word: " << result << endl;
return 0;
}
The time complexity analysis for this solution involves:
n is the length of the licensePlate.m is the number of words and k is the maximum length of a word.Overall, the time complexity is O(n + m * k), which is efficient for typical constraints expected in interviews.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?