LeetCode 890: Find and Replace Pattern Solution

Master LeetCode problem 890 (Find and Replace Pattern), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

890. Find and Replace Pattern

Problem Explanation

Explanation

To solve this problem, we need to iterate through each word in the given list of words and check if it matches the pattern. We can do this by creating a mapping of characters from the pattern to characters in the word and vice versa. If the mappings do not match, we move on to the next word. We can create two helper functions to handle the mappings and check if a word matches the pattern. The time complexity of this approach is O(N*M), where N is the number of words and M is the length of each word. The space complexity is O(M) for storing the mappings.

Solution Code

import java.util.*;

class Solution {
    public List<String> findAndReplacePattern(String[] words, String pattern) {
        List<String> result = new ArrayList<>();
        
        for (String word : words) {
            if (matchesPattern(word, pattern)) {
                result.add(word);
            }
        }
        
        return result;
    }
    
    private boolean matchesPattern(String word, String pattern) {
        if (word.length() != pattern.length()) {
            return false;
        }
        
        Map<Character, Character> wordToPattern = new HashMap<>();
        Map<Character, Character> patternToWord = new HashMap<>();
        
        for (int i = 0; i < word.length(); i++) {
            char w = word.charAt(i);
            char p = pattern.charAt(i);
            
            if (!wordToPattern.containsKey(w)) {
                wordToPattern.put(w, p);
            }
            
            if (!patternToWord.containsKey(p)) {
                patternToWord.put(p, w);
            }
            
            if (wordToPattern.get(w) != p || patternToWord.get(p) != w) {
                return false;
            }
        }
        
        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 890 (Find and Replace Pattern)?

This page provides optimized solutions for LeetCode problem 890 (Find and Replace Pattern) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 890 (Find and Replace Pattern)?

The time complexity for LeetCode 890 (Find and Replace Pattern) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 890 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 890 in Java, C++, or Python.

Back to LeetCode Solutions