09 Sept 2026Go / Python / TypeScriptEasy

Shortest Completing Word

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.

complexity

O(p + total word characters) time and O(1) space for fixed alphabet counts.

solution files

  • Go shortest-completing-word/solution.go
  • Python shortest-completing-word/solution.py
  • TypeScript shortest-completing-word/solution.ts

Solution files

Goshortest-completing-word/solution.go
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
}
Pythonshortest-completing-word/solution.py
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 = class="syntax-string">""
        for word in words:
            if (not answer or len(word) < len(answer)) and not (required - Counter(word.lower())):
                answer = word
        return answer
TypeScriptshortest-completing-word/solution.ts
function shortestCompletingWord(licensePlate: string, words: string[]): string {
  const required = new Array<number>(class="syntax-number">26).fill(class="syntax-number">0);
  for (const character of licensePlate.toLowerCase()) { const code = character.charCodeAt(class="syntax-number">0) - class="syntax-number">97; if (code >= class="syntax-number">0 && code < class="syntax-number">26) required[code] += class="syntax-number">1; }
  let answer = class="syntax-string">"";
  for (const word of words) {
    if (answer && answer.length <= word.length) continue;
    const count = new Array<number>(class="syntax-number">26).fill(class="syntax-number">0);
    for (const character of word.toLowerCase()) count[character.charCodeAt(class="syntax-number">0) - class="syntax-number">97] += class="syntax-number">1;
    if (required.every((needed, index) => count[index] >= needed)) answer = word;
  }
  return answer;
}