You get a license plate string, licensePlate, and a list of lower-case words. The plate may hold letters in either case, digits and spaces. Only its letters matter, and case does not.
A word completes the plate if it holds every plate letter at least as many times as the plate does. Return the shortest completing word. If several share that length, return the one that comes first in words. An answer always exists.
Example 1
Input: licensePlate = "Ab 3b", words = ["bat", "barb", "abbey", "bib"] Output: "barb" Why: it needs a, b, b; "barb" is the shortest word with them
2 more examples and the constraints
Example 2
Input: licensePlate = "7T 22", words = ["into", "cat", "hot", "tea"] Output: "cat" Why: three words of length 3 have a t; "cat" comes first
Example 3
Input: licensePlate = "QQ1", words = ["queue", "quiz", "qq"] Output: "qq" Why: only "qq" has two q's
Constraints
- 1 ≤ length of licensePlate ≤ 7, made of letters, digits and spaces
- 1 ≤ number of words ≤ 1,000
- 1 ≤ length of each word ≤ 15, lower-case letters only
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Cross letters offO(n·P·L)
- Count lettersO(P + n·L)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 1,000 words of 15 letters | Verdict |
|---|---|---|---|
| Cross letters off | O(n·P·L) | Works; repeats searches | |
| Count letters | O(P + n·L) | Best; count once per word |
n = number of words, L = length of a word, P = length of the plate.
Edge cases to test
- Repeated plate letter. "QQ1" needs two q's: "queue" has only one and does not count.
- Upper-case plate letters. "7T 22" needs a lower-case t; lower-case the plate before counting.
- Ties on length. "cat", "hot" and "tea" all fit "7T 22"; return the first, "cat".
- Plate letters only once. "barb" has extra letters; extra letters are fine.
- Shortest word appears last. The best can change late, so read every word.
Common mistakes
- Counting digits or spaces as letters to match.
- Forgetting to lower-case the plate, so 'T' never matches 't'.
- Replacing the best on equal length, which returns the last tied word instead of the first.
How to talk through it
- 1Clarify. Do digits and spaces count? Is case ignored? Which word wins a tie on length?
- 2Give the direct check. Cross each plate letter off a copy of the word; keep the shortest word that passes.
- 3Switch to counts. Only letter counts matter, so compare two 26-slot arrays instead of searching.
- 4Code it with the tie rule. Skip words that are not strictly shorter, so the first one wins.
- 5Test out loud. Run the repeated-letter and tie cases before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?