Find and Replace Pattern in Python

Finding and replacing patterns in Python involves identifying words that match a given character pattern structure. A word matches a pattern if there exists a character mapping where each unique character in the pattern maps consistently to characters in the word.

For example, with pattern "abb" and words ["abc", "deq", "mee", "aqq", "dkd", "ccc"], the words "mee" and "aqq" match because they follow the same structure: first character is unique, second and third characters are the same.

Algorithm Approach

The solution converts each word and the pattern into a normalized format representing the character structure. Characters are numbered based on their first appearance ?

Convert Function

This helper function transforms a word into its structural pattern ?

def convert(word):
    counter = 1
    s = ""
    s += str(counter)
    
    for i in range(1, len(word)):
        j = i - 1
        while j >= 0:
            if word[j] == word[i]:
                break
            j -= 1
        if j > -1:
            s += s[j]
        else:
            counter += 1
            s += str(counter)
    return s

# Test the convert function
print(convert("abb"))  # Pattern structure
print(convert("mee"))  # Same structure as "abb"
print(convert("abc"))  # Different structure
122
122
123

Complete Solution

Here's the complete implementation that finds all words matching the given pattern ?

class Solution:
    def findAndReplacePattern(self, words, pattern):
        words_num = []
        result = []
        
        # Convert all words to their structural patterns
        for word in words:
            words_num.append(self.convert(word))
        
        # Convert the target pattern
        pattern_structure = self.convert(pattern)
        
        # Find matching words
        for i in range(len(words)):
            if words_num[i] == pattern_structure:
                result.append(words[i])
        
        return result
    
    def convert(self, word):
        counter = 1
        s = ""
        s += str(counter)
        
        for i in range(1, len(word)):
            j = i - 1
            while j >= 0:
                if word[j] == word[i]:
                    break
                j -= 1
            if j > -1:
                s += s[j]
            else:
                counter += 1
                s += str(counter)
        return s

# Test the solution
solution = Solution()
words = ["abc", "deq", "mee", "aqq", "dkd", "ccc"]
pattern = "abb"
result = solution.findAndReplacePattern(words, pattern)
print(f"Words: {words}")
print(f"Pattern: {pattern}")
print(f"Matching words: {result}")
Words: ['abc', 'deq', 'mee', 'aqq', 'dkd', 'ccc']
Pattern: abb
Matching words: ['mee', 'aqq']

How It Works

The algorithm works by creating a structural signature for each word:

  • Step 1: Convert each word to a number pattern representing character positions
  • Step 2: Convert the target pattern using the same method
  • Step 3: Compare structural patterns and collect matches

For "abb": first char gets "1", second char gets "2", third char matches second so gets "2" ? "122"

For "mee": 'm' gets "1", first 'e' gets "2", second 'e' matches previous so gets "2" ? "122"

Alternative Implementation

Here's a more concise approach using Python's built-in functions ?

def findAndReplacePattern(words, pattern):
    def get_pattern(word):
        mapping = {}
        result = []
        counter = 0
        
        for char in word:
            if char not in mapping:
                mapping[char] = counter
                counter += 1
            result.append(mapping[char])
        return tuple(result)
    
    target_pattern = get_pattern(pattern)
    return [word for word in words if get_pattern(word) == target_pattern]

# Test the alternative solution
words = ["abc", "deq", "mee", "aqq", "dkd", "ccc"]
pattern = "abb"
result = findAndReplacePattern(words, pattern)
print(f"Result: {result}")
Result: ['mee', 'aqq']

Conclusion

Pattern matching in Python can be solved by converting words to structural representations and comparing them. The key insight is mapping each unique character to its first occurrence position, creating a signature that identifies the pattern structure regardless of the actual characters used.

Updated on: 2026-03-25T08:30:14+05:30

263 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements