Shortest Completing Word - Problem

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. Ignore numbers and spaces in licensePlate, and treat letters as case insensitive.

If a letter appears more than once in licensePlate, then it must appear in the word the same number of times or more.

For example, if licensePlate = "aBc 12c", then it contains letters 'a', 'b' (ignoring case), and 'c' twice. Possible completing words are "abccdef", "caaacab", and "cbca".

Return the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words.

Input & Output

Example 1 — Basic Case
$ Input: licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"]
Output: "steps"
💡 Note: The license plate contains letters 's', 'p', 't' (ignoring case and numbers). "step" has s:1, t:1, e:1, p:1 but missing required letters. "steps" has s:2, t:1, e:1, p:1 which covers all requirements. "stripe" and "stepple" are longer, so "steps" is the shortest completing word.
Example 2 — Multiple Same Letters
$ Input: licensePlate = "1s3 333", words = ["S", "sss", "look"]
Output: "sss"
💡 Note: The license plate contains only 's' (once). "S" has s:1 which satisfies the requirement and is shortest. Wait, let me recalculate: "S" has 1 character, "sss" has 3 characters, so "S" should be shorter and returned first.
Example 3 — Case Sensitivity
$ Input: licensePlate = "Ah71752", words = ["suggest", "letter", "of", "husband", "easy", "education", "drug", "prevent", "writer", "old"]
Output: "husband"
💡 Note: The license plate contains 'A' and 'h' (case insensitive, so 'a' and 'h'). "husband" contains both 'a' and 'h', and among valid words, it appears first in the array with reasonable length.

Constraints

  • 1 ≤ licensePlate.length ≤ 7
  • 1 ≤ words.length ≤ 1000
  • 1 ≤ words[i].length ≤ 15
  • licensePlate consists of digits, letters, and spaces
  • words[i] consists of lowercase English letters

Visualization

Tap to expand
Shortest Completing Word ProblemLicense: "1s3 PSt"Extract → s, p, t"step""steps""stripe""stepple"4 chars5 chars ✓6 chars7 charsMissing lettersHas s,p,tMissing lettersToo longResult: "steps"Find shortest word containing all required letters
Understanding the Visualization
1
Input
License plate "1s3 PSt" → letters: s,p,t
2
Process
Check each word for required letters
3
Output
Return shortest valid word
Key Takeaway
🎯 Key Insight: Use frequency counting to efficiently match letter requirements between license plate and candidate words
Asked in
Amazon 25 Microsoft 18 Google 15
25.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen