926. Find and Replace Pattern
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to filter a list of words, keeping only those that follow a specific pattern. A word "matches" the pattern if there's a consistent one-to-one mapping (a bijection) between the letters of the pattern and the letters of the word. This means each character in the pattern must map to a unique character in the word, and no two distinct pattern characters can map to the same word character.
Solution
Find and Replace Pattern in Python
class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
def normalize(s: str) -> str:
"""Converts a string to its canonical representation."""
# Map from character in s to a canonical character ('a', 'b', ...).
mapping = {}
# The next available canonical character, starting from 'a'.
next_char_ord = ord('a')
normalized_s = []
for char in s:
# If the character hasn't been seen before...
if char not in mapping:
# ...assign it the next available canonical character.
mapping[char] = chr(next_char_ord)
next_char_ord += 1
# Append the canonical character to the result list.
normalized_s.append(mapping[char])
return "".join(normalized_s)
# Normalize the pattern to a canonical form.
normalized_pattern = normalize(pattern)
result = []
# Iterate through each word in the list.
for word in words:
# If the normalized form of the word matches the normalized pattern,
# it's a valid match.
if normalize(word) == normalized_pattern:
result.append(word)
return result
Find and Replace Pattern in Java
class Solution {
public List<String> findAndReplacePattern(String[] words, String pattern) {
// Normalize the pattern to a canonical form.
String normalizedPattern = normalize(pattern);
List<String> result = new ArrayList<>();
// Iterate through each word in the list.
for (String word : words) {
// If the normalized form of the word matches the normalized pattern,
// it's a valid match.
if (normalize(word).equals(normalizedPattern)) {
result.add(word);
}
}
return result;
}
// Helper function to convert a string to its canonical representation.
private String normalize(String s) {
// Map from character in s to a canonical character ('a', 'b', ...).
Map<Character, Character> map = new HashMap<>();
char nextChar = 'a';
StringBuilder normalizedS = new StringBuilder();
for (char c : s.toCharArray()) {
// If the character hasn't been seen before, put it in the map
// with the next available canonical character.
map.putIfAbsent(c, nextChar);
if (map.get(c) == nextChar) { // This check ensures nextChar is only incremented when a new key is added.
nextChar++;
}
// Append the canonical character to the result string.
normalizedS.append(map.get(c));
}
return normalizedS.toString();
}
}
Find and Replace Pattern in C++
class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
// Normalize the pattern to a canonical form.
string normalized_pattern = normalize(pattern);
vector<string> result;
// Iterate through each word in the list.
for (const string& word : words) {
// If the normalized form of the word matches the normalized pattern,
// it's a valid match.
if (normalize(word) == normalized_pattern) {
result.push_back(word);
}
}
return result;
}
private:
// Helper function to convert a string to its canonical representation.
string normalize(const string& s) {
// Map from character in s to a canonical character ('a', 'b', ...).
// Using an array for efficiency since characters are lowercase English letters.
char map[26] = {0};
char next_char = 'a';
string normalized_s = "";
for (char c : s) {
// If the character hasn't been seen before...
if (map[c - 'a'] == 0) {
// ...assign it the next available canonical character.
map[c - 'a'] = next_char;
next_char++;
}
// Append the canonical character to the result string.
normalized_s += map[c - 'a'];
}
return normalized_s;
}
};
Find and Replace Pattern in TypeScript
function findAndReplacePattern(words: string[], pattern: string): string[] {
// Helper function to convert a string to its canonical representation.
const normalize = (s: string): string => {
// Map from character in s to a canonical character ('a', 'b', ...).
const map = new Map<string, string>();
// The next available canonical character, starting from 'a'.
let nextChar = 'a';
let normalizedS = '';
for (const char of s) {
// If the character hasn't been seen before...
if (!map.has(char)) {
// ...assign it the next available canonical character.
map.set(char, nextChar);
nextChar = String.fromCharCode(nextChar.charCodeAt(0) + 1);
}
// Append the canonical character to the result string.
normalizedS += map.get(char);
}
return normalizedS;
};
// Normalize the pattern to a canonical form.
const normalizedPattern = normalize(pattern);
const result: string[] = [];
// Iterate through each word in the list.
for (const word of words) {
// If the normalized form of the word matches the normalized pattern,
// it's a valid match.
if (normalize(word) === normalizedPattern) {
result.push(word);
}
}
return result;
// A more concise functional approach using filter:
/*
const normalizedPattern = normalize(pattern);
return words.filter(word => normalize(word) === normalizedPattern);
*/
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.