Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Find and Replace Pattern

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "890" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order. A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word. Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter. Example 1: Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb" Output: ["mee","aqq"] Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. "ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter. Example 2: Input: words = ["a","b","c"], pattern = "a" Output: ["a","b","c"] Constraints: 1 <= pattern.length <= 20 1 <= words.length <= 50 words[i].length == pattern.length pattern and words[i] are lowercase English letters.

Explanation

Here's the breakdown of the solution:

  • Normalize the pattern and words: Convert both the pattern and each word into a canonical form. This form represents the relative positions of characters. For example, "abb" becomes "011" because the first character is 'a' (0), the second is 'b' (1), and the third is also 'b' (1). "mee" and "aqq" would also become "011".
  • Compare normalized forms: If the normalized form of a word matches the normalized form of the pattern, then that word matches the pattern.
  • Store results: Collect the matching words in a list and return it.

  • Runtime Complexity: O(N M), where N is the number of words and M is the length of the pattern (and each word). *Storage Complexity: O(M)

Code

    def find_and_replace_pattern(words, pattern):
    """
    Finds words that match a given pattern.

    Args:
        words: A list of strings.
        pattern: A string pattern.

    Returns:
        A list of words that match the pattern.
    """

    def normalize(s):
        """
        Normalizes a string to a canonical form based on character positions.

        Args:
            s: The input string.

        Returns:
            A string representing the normalized form.
        """
        mapping = {}
        next_id = 0
        normalized = ""
        for char in s:
            if char not in mapping:
                mapping[char] = str(next_id)
                next_id += 1
            normalized += mapping[char]
        return normalized

    normalized_pattern = normalize(pattern)
    result = []
    for word in words:
        if normalize(word) == normalized_pattern:
            result.append(word)
    return result

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Find and Replace Pattern