EasyNo. 0748

Shortest Completing Word — LeetCode 748 Python Solution

Pattern
Hash Map
Topics
Array, Hash Table, String
Reading time
2 min

The 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.

Example

Input
licensePlate = "1s3 PSt", words = ["step","steps","stripe","stepple"]
Output
"steps"
Explanation
licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.

Python solution

PythonSolution
class Solution:
    def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
        cnt = Counter(c.lower() for c in licensePlate if c.isalpha())
        ans = None
        for w in words:
            if ans and len(w) >= len(ans):
                continue
            t = Counter(w)
            if all(v <= t[c] for c, v in cnt.items()):
                ans = w
        return ans

Complexity

Time
O(n × |Σ|)
Space · auxiliary
O(|Σ|)

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 748. Shortest Completing Word is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0745Prefix and Suffix SearchHard
0752Open the LockMedium
0049Group AnagramsMedium
0139Word BreakMedium
0140Word Break IIHard
0336Palindrome PairsHard

Frequently asked questions

How hard is LeetCode 748. Shortest Completing Word?

LeetCode 748. Shortest Completing Word is rated Easy on LeetCode.

What is the time complexity of LeetCode 748. Shortest Completing Word?

The Python solution on this page runs in O(n × |Σ|).

What is the space complexity of LeetCode 748. Shortest Completing Word?

The Python solution on this page uses O(|Σ|) auxiliary space.

What topics does LeetCode 748. Shortest Completing Word cover?

LeetCode 748. Shortest Completing Word is tagged Array, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.