The problem statement for LeetCode 748: Shortest Completing Word is as follows:
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 licensePlate (ignoring numbers and case). If multiple completing words are found, return the shortest one. If there is a tie, return the first one that appears in the given array ‘words’.
Input: licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"]
Output: "steps"
licensePlate
for forming the completing words?
licensePlate
.licensePlate
?
words
.licensePlate
and convert them to lowercase.licensePlate
.words
array:
licensePlate
frequency.Below is the Python solution to solve the problem:
from collections import Counter
def shortestCompletingWord(licensePlate, words):
# Filter and count letters from the license plate
license_count = Counter(char.lower() for char in licensePlate if char.isalpha())
def is_completing(word):
word_count = Counter(word)
for char, count in license_count.items():
if word_count[char] < count:
return False
return True
shortest_word = None
for word in words:
lower_word = word.lower()
if is_completing(lower_word):
if shortest_word is None or len(word) < len(shortest_word):
shortest_word = word
return shortest_word
# Example usage
licensePlate = "1s3 PSt"
words = ["step", "steps", "stripe", "stepple"]
print(shortestCompletingWord(licensePlate, words)) # Output: "steps"
licensePlate
.w
words each of maximum length l
), it takes O(l) to check frequency completeness.Overall, the complexity is O(n + m + w*l)
, which can be approximated as O(w*l)
in scenarios where the length of licensePlate
and the number of words is significantly smaller compared to the total characters in all words combined.
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?