Problem 890

Abstract / Summary

Find all words in a list that have the same letter pattern as a given word and return them.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0890.py

class Solution:
    def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
        def numeric(word):
            # assign IDs to each letter
            # the first letter gets assigned 0, the second gets 1, ...
            nums = []
            have = {}
            for c in word:
                if c not in have:
                    have[c] = len(have) # generate new ID
                nums.append(have[c])    # use ID
            return nums

        p2n = numeric(pattern)
        for w in words:
            if numeric(w) == p2n:
                yield w
17 lines | 603 bytes | submitted December 4, 2023 | GitHub   28% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 77% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a method findAndReplacePattern. The method receives a list of words and a pattern string, and it yields every word whose internal character structure matches that of the pattern. The core idea is to transform each word and the pattern into a sequence of numeric identifiers that capture the order of first appearances of characters. By comparing these numeric sequences, the algorithm determines whether a word follows the same pattern.

Numeric Mapping

A nested helper function numeric performs the conversion from a string to its numeric representation. The function iterates over each character, assigns a unique identifier to the first occurrence of each distinct character, and records the identifier for every character in the order they appear.

def numeric(word):
    nums = []
    have = {}
    for c in word:
        if c not in have:
            have[c] = len(have)   # first unseen character gets the next ID
        nums.append(have[c])       # record the ID for the current character
    return nums

The mapping guarantees that two strings with identical patterns will produce identical numeric lists, regardless of the actual letters used.

Pattern Matching Loop

After computing the numeric representation of the pattern, the method iterates over the supplied words. For each word, it computes its numeric representation on the fly and compares it directly to the pattern’s numeric list. When the two lists are equal, the word satisfies the pattern and is yielded.

p2n = numeric(pattern)
for w in words:
    if numeric(w) == p2n:
        yield w

The use of a generator (yield) allows the caller to consume matching words lazily, which can be advantageous when only a subset of results is needed.

Edge Cases Handled

The algorithm naturally accommodates several edge conditions:

  • Empty pattern: When pattern is an empty string, numeric(pattern) returns an empty list. Any word that is also empty will produce an empty numeric list, causing a match. Non-empty words generate non-empty numeric lists and therefore do not match.
  • Single-character words: For a pattern consisting of a single character, the numeric representation is [0]. Any single-character word, regardless of its actual letter, will also map to [0], resulting in a match.
  • Repeated characters: The mapping records the first occurrence index for each character. Consequently, patterns with repeated letters (e.g., "abb") generate a numeric list like [0, 1, 1]. Words with the same repetition structure (e.g., "mee") will produce the same list, while words with different repetition patterns will not match.
  • Distinct characters with same count: Patterns where all characters are distinct (e.g., "abc") map to [0, 1, 2]. Any word with three distinct letters, irrespective of their actual values, will match, while words containing any repeated letter will produce a different numeric list and be excluded.

Performance Considerations

The implementation exhibits several performance-oriented characteristics:

  • On-the-fly computation: The numeric representation of each word is computed only when needed, avoiding the storage of intermediate results for all words. This reduces memory overhead, especially when the input list is large.
  • Dictionary-based ID assignment: Using a Python dictionary (have) to map characters to identifiers provides average-case constant-time lookups and insertions. The identifier is derived from the current size of the dictionary (len(have)), which eliminates the need for a separate counter variable.
  • Early termination of comparison: The equality check numeric(w) == p2n leverages Python’s list comparison, which stops at the first mismatching element. For words that diverge early from the pattern, the comparison finishes quickly, saving unnecessary work.
  • Generator output: By yielding matching words instead of building a list, the method avoids allocating a potentially large result container. This is particularly beneficial when the caller consumes the generator incrementally or stops after a few matches.

Overall, the code delivers a concise solution that translates pattern matching into a numeric equivalence problem, handling a variety of input shapes while maintaining low memory usage and leveraging Python’s built-in data structures for efficient execution.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a group of secret agents who speak in a special code. Each word is like a row of colored blocks. To figure out if a word matches a pattern, we turn both into a list of numbers. When the computer sees a letter for the first time, it gives it a new number starting from zero. If it sees that same letter again later, it uses the number it saved earlier.

The computer looks at the secret pattern and turns it into a list of these numbers. Then, it goes through every word in the list one by one and turns them into numbers just like the pattern. If the secret pattern of numbers matches the word’s pattern of numbers perfectly, that word gets to be part of the final answer.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.11 | σ = 1.23

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fengvyi C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
muhammadfarhankt Go
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fengvyi C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
muhammadfarhankt Go
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
YuriSpiridonov Python
38 links | 24 authors | 9 languages

Videos

10 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

12 solutions   December 4, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality