Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

890. Find and Replace Pattern

ArrayHash TableString

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.

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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.