291. Word Pattern II
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 determine if a string s follows a given pattern. This match requires a bijective mapping between characters in the pattern and non-empty substrings in s. A bijective mapping means every character in the pattern maps to a unique non-empty substring, and no two different characters map to the same substring. The core challenge is that the lengths of these substrings are unknown. We need to explore different ways of partitioning s to see if any partition satisfies the pattern's constraints. This structure naturally suggests a search algorithm, and backtracking is a perfect fit.
Solution
Word Pattern II in Python
class Solution:
def wordPatternMatch(self, pattern: str, s: str) -> bool:
self.memo = {}
return self.backtrack(pattern, 0, s, 0, {}, set())
def backtrack(self, pattern, p_idx, s, s_idx, char_to_str, used_strs):
# Base case: if pattern is exhausted, s must also be exhausted
if p_idx == len(pattern):
return s_idx == len(s)
# Get the current pattern character
p_char = pattern[p_idx]
# Case 1: The pattern character is already mapped
if p_char in char_to_str:
mapped_str = char_to_str[p_char]
# Check if s has this string at the current position
if not s.startswith(mapped_str, s_idx):
return False
# If it matches, recurse
return self.backtrack(pattern, p_idx + 1, s, s_idx + len(mapped_str), char_to_str, used_strs)
# Case 2: New pattern character, try all possible non-empty substrings
for i in range(s_idx, len(s)):
candidate_str = s[s_idx : i + 1]
# Pruning: if remaining pattern is longer than remaining string, no solution possible
if len(pattern) - (p_idx + 1) > len(s) - (i + 1):
break
# If candidate_str is already used by another char, skip
if candidate_str in used_strs:
continue
# Try this mapping
char_to_str[p_char] = candidate_str
used_strs.add(candidate_str)
# Recurse
if self.backtrack(pattern, p_idx + 1, s, i + 1, char_to_str, used_strs):
return True
# Backtrack
del char_to_str[p_char]
used_strs.remove(candidate_str)
# No valid mapping found
return False
Word Pattern II in Java
class Solution {
public boolean wordPatternMatch(String pattern, String s) {
Map<Character, String> charToStr = new HashMap<>();
Set<String> usedStrs = new HashSet<>();
return backtrack(pattern, 0, s, 0, charToStr, usedStrs);
}
private boolean backtrack(String pattern, int pIdx, String s, int sIdx,
Map<Character, String> charToStr, Set<String> usedStrs) {
// Base case: If we've matched the entire pattern
if (pIdx == pattern.length()) {
// Return true only if we've also consumed the entire string s
return sIdx == s.length();
}
// Get the current pattern character
char pChar = pattern.charAt(pIdx);
// Case 1: The pattern character is already in the map
if (charToStr.containsKey(pChar)) {
String mappedStr = charToStr.get(pChar);
// Check if the string s has the mapped string as a prefix at sIdx
if (!s.startsWith(mappedStr, sIdx)) {
return false; // Mismatch
}
// If it matches, recurse for the rest of the pattern and string
return backtrack(pattern, pIdx + 1, s, sIdx + mappedStr.length(), charToStr, usedStrs);
}
// Case 2: The pattern character is new, try all possible mappings
for (int i = sIdx; i < s.length(); ++i) {
String candidateStr = s.substring(sIdx, i + 1);
// Pruning: if remaining s is shorter than remaining pattern, no solution possible
// from this point on. Since loop for i increases candidateStr length, remaining
// s will only get shorter, so we can break.
if (pattern.length() - pIdx - 1 > s.length() - i - 1) {
break;
}
// If the candidate string has already been mapped to another character, skip
if (usedStrs.contains(candidateStr)) {
continue;
}
// Try this mapping
charToStr.put(pChar, candidateStr);
usedStrs.add(candidateStr);
// Recurse
if (backtrack(pattern, pIdx + 1, s, i + 1, charToStr, usedStrs)) {
return true; // Solution found
}
// Backtrack: undo the mapping
charToStr.remove(pChar);
usedStrs.remove(candidateStr);
}
// No mapping worked for this character
return false;
}
}
Word Pattern II in C++
class Solution {
public:
bool wordPatternMatch(string pattern, string s) {
unordered_map<char, string> char_to_str;
unordered_set<string> used_strs;
return backtrack(pattern, 0, s, 0, char_to_str, used_strs);
}
private:
bool backtrack(const string& pattern, int p_idx, const string& s, int s_idx,
unordered_map<char, string>& char_to_str, unordered_set<string>& used_strs) {
// Base case: If we've matched the entire pattern
if (p_idx == pattern.length()) {
// Return true only if we've also consumed the entire string s
return s_idx == s.length();
}
// Get the current pattern character
char p_char = pattern[p_idx];
// Case 1: The pattern character is already in the map
if (char_to_str.count(p_char)) {
string mapped_str = char_to_str[p_char];
// Check if the string s has the mapped string as a prefix at s_idx
if (s.rfind(mapped_str, s_idx) != s_idx) { // s.rfind is an alternative to s.compare or s.substr
return false; // Mismatch
}
// If it matches, recurse for the rest of the pattern and string
return backtrack(pattern, p_idx + 1, s, s_idx + mapped_str.length(), char_to_str, used_strs);
}
// Case 2: The pattern character is new, try all possible mappings
for (int i = s_idx; i < s.length(); ++i) {
string candidate_str = s.substr(s_idx, i - s_idx + 1);
// Pruning: if remaining s is shorter than remaining pattern, no solution possible
if (pattern.length() - p_idx - 1 > s.length() - i - 1) {
continue;
}
// If the candidate string has already been mapped to another character, skip
if (used_strs.count(candidate_str)) {
continue;
}
// Try this mapping
char_to_str[p_char] = candidate_str;
used_strs.insert(candidate_str);
// Recurse
if (backtrack(pattern, p_idx + 1, s, i + 1, char_to_str, used_strs)) {
return true; // Solution found
}
// Backtrack: undo the mapping
char_to_str.erase(p_char);
used_strs.erase(candidate_str);
}
// No mapping worked for this character
return false;
}
};
Word Pattern II in TypeScript
function wordPatternMatch(pattern: string, s: string): boolean {
const charToStr = new Map<string, string>();
const usedStrs = new Set<string>();
function backtrack(pIdx: number, sIdx: number): boolean {
// Base case: If we've matched the entire pattern
if (pIdx === pattern.length) {
// Return true only if we've also consumed the entire string s
return sIdx === s.length;
}
// Get the current pattern character
const pChar = pattern[pIdx];
// Case 1: The pattern character is already in the map
if (charToStr.has(pChar)) {
const mappedStr = charToStr.get(pChar)!;
// Check if the string s has the mapped string as a prefix at sIdx
if (!s.startsWith(mappedStr, sIdx)) {
return false; // Mismatch
}
// If it matches, recurse for the rest of the pattern and string
return backtrack(pIdx + 1, sIdx + mappedStr.length);
}
// Case 2: The pattern character is new, try all possible mappings
for (let i = sIdx; i < s.length; i++) {
const candidateStr = s.substring(sIdx, i + 1);
// Pruning: if remaining s is shorter than remaining pattern, no solution possible
if (pattern.length - (pIdx + 1) > s.length - (i + 1)) {
break;
}
// If the candidate string has already been mapped to another character, skip
if (usedStrs.has(candidateStr)) {
continue;
}
// Try this mapping
charToStr.set(pChar, candidateStr);
usedStrs.add(candidateStr);
// Recurse
if (backtrack(pIdx + 1, i + 1)) {
return true; // Solution found
}
// Backtrack: undo the mapping
charToStr.delete(pChar);
usedStrs.delete(candidateStr);
}
// No mapping worked for this character
return false;
}
return backtrack(0, 0);
}
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.