Find and Replace Pattern (LeetCode 890): Solution and Explanation

Medium
Array
Hash Table
String

Return every word whose letters can be renamed one to one to spell the pattern.

Intuition

A word matches when there is a renaming of letters that turns the pattern into the word. The renaming must be one to one: a pattern letter always becomes the same word letter, and two different pattern letters never become the same one.

Walking the word and the pattern side by side, every position proposes a pair. The word matches exactly when all proposed pairs agree with each other.

One map from word letter to pattern letter only catches half of the failures. With pattern "ccc" and word "abc", that map sends a, b and c all to c without any contradiction. Only a reverse map, from pattern letter to word letter, notices that c is claimed three times.

Approach: Two maps for a bijection

  1. For each word, create two empty maps: fwd from word letter to pattern letter and bwd from pattern letter to word letter.
  2. At position i, take a = w[i] and b = pattern[i]. If a is new, set fwd[a] = b. If b is new, set bwd[b] = a.
  3. If fwd[a] is not b or bwd[b] is not a, the pairing is broken and the word fails.
  4. If every position agrees, add the word to the result.

Step-by-step example

words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
  1. "abc": a pairs with a, b with b, then c meets pattern letter b, which is already taken by b. Rejected.
  2. "deq": q meets pattern b, already taken by e. Rejected.
  3. "mee": m pairs with a, e with b, and the last e agrees with e to b. Kept.
  4. "aqq": a with a, q with b, then q again with b. Kept.
  5. "dkd": the last d already stands for a but sits under b. Rejected.
  6. "ccc": c stands for a, then sits under b. Rejected. Return ["mee","aqq"].

Code: Python, Java, C++

1class Solution:
2    def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
3        result = []
4        for w in words:
5            fwd, bwd = {}, {}
6            ok = True
7            for a, b in zip(w, pattern):
8                fwd.setdefault(a, b)
9                bwd.setdefault(b, a)
10                if fwd[a] != b or bwd[b] != a:
11                    ok = False
12                    break
13            if ok:
14                result.append(w)
15        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n * m)

Each of the n words is scanned once over its m letters, with constant work per letter.

Space

O(1)

Each map holds at most 26 entries, not counting the output list.

Other approaches

Normalize to first-occurrence indices (time O(n * m), space O(m))

Replace each letter by the index where it first appears, so "mee" and "abb" both become [0,1,1]. A word matches when its normalized form equals the pattern's. Same complexity, one array per word.

Common mistakes

  • Checking only the word to pattern direction. The word "abc" against pattern "ccc" passes that check, so it would be wrongly accepted without the reverse map.
  • Reusing the maps from the previous word instead of starting fresh for each word.
  • Comparing letter counts or sorted letters, which ignores where the letters sit.

Frequently asked questions

Why are two maps needed?

The forward map stops one word letter from standing for two pattern letters. The backward map stops two word letters from standing for the same pattern letter. A bijection needs both.

Does the order of the output matter?

No. Any order is accepted. This solution returns matches in the order they appear in words.

How is this related to Isomorphic Strings?

It is the same test, run once per word. Isomorphic Strings asks whether two strings pair up one to one; here the pattern is compared with every word.