Shortest Completing Word in Python

The Shortest Completing Word problem requires finding the shortest word from a dictionary that contains all letters from a given license plate. The word must include each letter at least as many times as it appears in the license plate, ignoring case and non-alphabetic characters.

For example, if the license plate is "PP", the word "pile" doesn't work because it only has one 'P', but "topper" works because it has two 'P's.

Problem Understanding

Given a license plate string and a list of words, we need to:

  • Extract only alphabetic characters from the license plate (ignore numbers and symbols)
  • Find words that contain all required letters with sufficient frequency
  • Return the shortest valid word (first occurrence if tie)

Algorithm Steps

To solve this problem, we follow these steps:

  • Extract alphabetic characters from license plate and convert to lowercase
  • For each word in the dictionary, check if it contains all required letters
  • Count letter frequencies to ensure sufficient occurrences
  • Return the shortest word that satisfies all conditions

Implementation

class Solution:
    def shortestCompletingWord(self, licensePlate, words):
        alphabet = "abcdefghijklmnopqrstuvwxyz"
        letters = [s.lower() for s in licensePlate if s.lower() in alphabet]
        valid_words = []
        
        for word in words:
            is_valid = True
            for letter in letters:
                if letters.count(letter) > word.count(letter):
                    is_valid = False
                    break
            if is_valid:
                valid_words.append(word)
        
        return min(valid_words, key=len)

# Test the solution
ob = Solution()
result = ob.shortestCompletingWord("1s3 PSt", ["step", "steps", "stripe", "stepple"])
print(result)
steps

How It Works

Let's trace through the example with licensePlate = "1s3 PSt":

  1. Extract letters: ['s', 'p', 's', 't'] (ignoring '1', '3', and space)
  2. Check each word:
    • "step": has 1 's', 1 'p', 1 't' ? Missing one 's' ? Invalid
    • "steps": has 2 's', 1 'p', 1 't' ? Valid
    • "stripe": has 1 's', 1 'p', 1 't' ? Missing one 's' ? Invalid
    • "stepple": has 1 's', 2 'p', 1 't' ? Missing one 's' ? Invalid
  3. Only "steps" is valid, so it's returned

Optimized Solution

We can optimize using Counter from collections to handle letter frequency more efficiently:

from collections import Counter

class Solution:
    def shortestCompletingWord(self, licensePlate, words):
        # Count letter frequencies in license plate
        plate_letters = Counter(c.lower() for c in licensePlate if c.isalpha())
        
        valid_words = []
        for word in words:
            word_letters = Counter(word.lower())
            # Check if word contains all required letters
            if all(word_letters[letter] >= count for letter, count in plate_letters.items()):
                valid_words.append(word)
        
        return min(valid_words, key=len)

# Test the optimized solution
ob = Solution()
result = ob.shortestCompletingWord("1s3 PSt", ["step", "steps", "stripe", "stepple"])
print(result)
steps

Key Points

  • Case insensitive: Convert all letters to lowercase for comparison
  • Frequency matters: Word must contain each letter at least as many times as in license plate
  • Shortest first: Return the word with minimum length among valid options
  • First occurrence: If multiple words have same minimum length, return the first one

Conclusion

The shortest completing word problem combines string processing with frequency counting. The optimized solution using Counter provides better readability and performance for handling letter frequencies efficiently.

Updated on: 2026-03-25T08:49:47+05:30

456 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements