Count the plate's letters case-insensitively, then scan words in order and keep the first shortest word whose counts cover every requirement.
Complexity
O(p + total word characters) time and O(1) space for fixed alphabet counts.
Find the shortest word containing every letter required by a license plate.
Count the plate's letters case-insensitively, then scan words in order and keep the first shortest word whose counts cover every requirement.
O(p + total word characters) time and O(1) space for fixed alphabet counts.
package main
import "unicode"
func shortestCompletingWord(licensePlate string, words []string) string {
var required [26]int
for _, character := range licensePlate {
lower := unicode.ToLower(character)
if lower >= 'a' && lower <= 'z' {
required[lower-'a']++
}
}
answer := ""
for _, word := range words {
if answer != "" && len(answer) <= len(word) {
continue
}
var count [26]int
for _, character := range word {
count[unicode.ToLower(character)-'a']++
}
valid := true
for index, needed := range required {
if count[index] < needed {
valid = false
break
}
}
if valid {
answer = word
}
}
return answer
}
from collections import Counter
class Solution:
def shortestCompletingWord(self, licensePlate: str, words: list[str]) -> str:
required = Counter(character for character in licensePlate.lower() if character.isalpha())
answer = ""
for word in words:
if (not answer or len(word) < len(answer)) and not (required - Counter(word.lower())):
answer = word
return answer
function shortestCompletingWord(licensePlate: string, words: string[]): string {
const required = new Array<number>(26).fill(0);
for (const character of licensePlate.toLowerCase()) { const code = character.charCodeAt(0) - 97; if (code >= 0 && code < 26) required[code] += 1; }
let answer = "";
for (const word of words) {
if (answer && answer.length <= word.length) continue;
const count = new Array<number>(26).fill(0);
for (const character of word.toLowerCase()) count[character.charCodeAt(0) - 97] += 1;
if (required.every((needed, index) => count[index] >= needed)) answer = word;
}
return answer;
}