Shortest Completing Word - Problem
You're given a license plate and a list of candidate words. Your mission is to find the shortest word that contains all the letters from the license plate!
Rules:
- ๐ค Only letters matter - ignore numbers and spaces in the license plate
- ๐ Case doesn't matter - treat 'A' and 'a' as the same
- ๐ข If a letter appears multiple times in the license plate, the word must have at least that many occurrences
- ๐ Return the shortest completing word. If there's a tie, return the first one
Example: If licensePlate = "aBc 12c", you need a word with at least: 1ร'a', 1ร'b', and 2ร'c'. Words like "abccdef" or "caaacab" would work!
Input & Output
example_1.py โ Basic Example
$
Input:
licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"]
โบ
Output:
"steps"
๐ก Note:
License plate contains letters: s, P, s, t โ s(2), p(1), t(1). 'steps' is the shortest word containing at least 2 s's, 1 p, and 1 t.
example_2.py โ Case Insensitive
$
Input:
licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"]
โบ
Output:
"pest"
๐ก Note:
License plate contains only 's' (case insensitive). All words contain 's', but 'pest' is shortest at 4 characters.
example_3.py โ Multiple Requirements
$
Input:
licensePlate = "Ah71752", words = ["suggest", "letter", "of", "husband", "easy", "education", "drug", "prevent", "writer", "old"]
โบ
Output:
"husband"
๐ก Note:
License plate contains 'A' and 'h' (case insensitive: a(1), h(1)). 'husband' contains both required letters and is the first shortest match.
Visualization
Tap to expand
Understanding the Visualization
1
Extract Recipe Requirements
From 'aBc 12c', extract letters: a(1), b(1), c(2) - ignore numbers and spaces
2
Build Shopping List
Create frequency map showing exactly what letters and quantities we need
3
Check Each Recipe
For each word, count its letters and verify it has enough of each required letter
4
Find Shortest Match
Among valid words, return the shortest one (first in case of ties)
Key Takeaway
๐ฏ Key Insight: By preprocessing the license plate requirements once and reusing them for all word validations, we avoid redundant work and achieve optimal O(k + mรn) time complexity.
Time & Space Complexity
Time Complexity
O(m ร n ร k)
Where m is number of words, n is average word length, and k is license plate length. We process the license plate k times for each of m words.
โ Linear Growth
Space Complexity
O(1)
Only using a few variables to track counts and the current best word
โ Linear Space
Constraints
- 1 โค licensePlate.length โค 7
- 1 โค words.length โค 1000
- 1 โค words[i].length โค 15
- licensePlate and words[i] consist of uppercase and lowercase English letters and digits
- It is guaranteed that an answer exists
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code