Word Pattern II
Word Pattern II is a medium recursion & backtracking problem solved with the choice per position pattern.
The best approach, optimal (backtracking with length pruning), runs in O(n^m) time and O(m + n) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (try every split) up.
Problem
You are given a pattern and a string s. Return true if s matches the pattern, and false otherwise.
s matches pattern when every letter of the pattern can be assigned a non-empty string so that writing those strings in pattern order, with nothing in between, gives exactly s. The assignment must be one-to-one: each pattern letter always stands for the same string, and two different letters never stand for the same string.
Examples
Example 1
- Input
pattern = "abab", s = "redbluredblu"- Output
true- Why
- Let a stand for "red" and b for "blu". Then abab spells red, blu, red, blu, which is exactly s.
Example 2
- Input
pattern = "aaaa", s = "xyzxyzxyzxyz"- Output
true- Why
- a stands for "xyz", and four copies of it make s.
Example 3
- Input
pattern = "aabb", s = "catcatdogcat"- Output
false- Why
- The first a must be some prefix w, then s must start with w w. Only w = "cat" works. Then b b must spell the rest, "dogcat", which would need "dog" and "cat" to be the same string.
Example 4
- Input
pattern = "ab", s = "zz"- Output
false- Why
- The only split is "z" and "z", but a and b are different letters, so they may not both stand for "z".
Constraints
1 <= pattern.length, s.length <= 20patternandsconsist only of lowercase English letters.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (4 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (try every split) | O(C(n - 1, m - 1) * n) | O(n) |
| Backtracking with a map and a used set | O(n^m) | O(m + n) |
| Optimal (backtracking with length pruning) | O(n^m) | O(m + n) |
1Brute force (try every split)
O(C(n - 1, m - 1) * n)There are C(n - 1, m - 1) ways to place m - 1 cuts in the n - 1 gaps of s, and checking one split reads all n characters.O(n)The recursion is m deep and the pieces and maps together hold the n characters of s.Every candidate answer is a way to cut s into exactly pattern.length non-empty pieces. Generate all of them by choosing where each piece ends, and for every complete split check the rule directly: walk the pattern with two maps, letter to piece and piece to letter, and fail as soon as either map disagrees. The first split that passes proves the answer is true. This never uses what it learns early: a split whose first two pieces already clash is still extended all the way before it is checked.
- Recursively choose the end of each piece, from position start onward, until pattern.length pieces are chosen.
- A complete split counts only if it uses all of s. Check it with two maps: letter to piece and piece to letter must both stay consistent.
- Return true on the first split that passes; false if none does.
class Solution {
public boolean wordPatternMatch(String pattern, String s) {
return split(pattern, s, 0, new ArrayList<>());
}
private boolean split(String pattern, String s, int start, List<String> pieces) {
if (pieces.size() == pattern.length()) {
return start == s.length() && fits(pattern, pieces);
}
for (int end = start + 1; end <= s.length(); end++) {
pieces.add(s.substring(start, end));
if (split(pattern, s, end, pieces)) return true;
pieces.remove(pieces.size() - 1);
}
return false;
}
private boolean fits(String pattern, List<String> pieces) {
Map<Character, String> toPiece = new HashMap<>();
Map<String, Character> toLetter = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
String w = pieces.get(i);
if (toPiece.containsKey(c) && !toPiece.get(c).equals(w)) return false;
if (toLetter.containsKey(w) && toLetter.get(w) != c) return false;
toPiece.put(c, w);
toLetter.put(w, c);
}
return true;
}
}class Solution:
def wordPatternMatch(self, pattern: str, s: str) -> bool:
return self.split(pattern, s, 0, [])
def split(self, pattern: str, s: str, start: int, pieces: List[str]) -> bool:
if len(pieces) == len(pattern):
return start == len(s) and self.fits(pattern, pieces)
for end in range(start + 1, len(s) + 1):
pieces.append(s[start:end])
if self.split(pattern, s, end, pieces):
return True
pieces.pop()
return False
def fits(self, pattern: str, pieces: List[str]) -> bool:
to_piece = {}
to_letter = {}
for c, w in zip(pattern, pieces):
if c in to_piece and to_piece[c] != w:
return False
if w in to_letter and to_letter[w] != c:
return False
to_piece[c] = w
to_letter[w] = c
return Trueclass Solution {
public:
bool wordPatternMatch(string pattern, string s) {
vector<string> pieces;
return split(pattern, s, 0, pieces);
}
private:
bool split(const string& pattern, const string& s, int start, vector<string>& pieces) {
if (pieces.size() == pattern.size()) {
return start == (int) s.size() && fits(pattern, pieces);
}
for (int end = start + 1; end <= (int) s.size(); end++) {
pieces.push_back(s.substr(start, end - start));
if (split(pattern, s, end, pieces)) return true;
pieces.pop_back();
}
return false;
}
bool fits(const string& pattern, const vector<string>& pieces) {
unordered_map<char, string> toPiece;
unordered_map<string, char> toLetter;
for (int i = 0; i < (int) pattern.size(); i++) {
char c = pattern[i];
const string& w = pieces[i];
if (toPiece.count(c) && toPiece[c] != w) return false;
if (toLetter.count(w) && toLetter[w] != c) return false;
toPiece[c] = w;
toLetter[w] = c;
}
return true;
}
};function wordPatternMatch(pattern, s) {
return split(pattern, s, 0, []);
}
function split(pattern, s, start, pieces) {
if (pieces.length === pattern.length) {
return start === s.length && fits(pattern, pieces);
}
for (let end = start + 1; end <= s.length; end++) {
pieces.push(s.substring(start, end));
if (split(pattern, s, end, pieces)) return true;
pieces.pop();
}
return false;
}
function fits(pattern, pieces) {
const toPiece = new Map();
const toLetter = new Map();
for (let i = 0; i < pattern.length; i++) {
const c = pattern[i];
const w = pieces[i];
if (toPiece.has(c) && toPiece.get(c) !== w) return false;
if (toLetter.has(w) && toLetter.get(w) !== c) return false;
toPiece.set(c, w);
toLetter.set(w, c);
}
return true;
}2Backtracking with a map and a used set
O(n^m)In the worst case each of the m pattern letters tries up to n piece lengths, but repeated letters cost no branching and clashes cut branches early, so real inputs explore far fewer calls.O(m + n)The recursion is at most m deep, and the map and set hold at most 26 pieces whose total length is at most n.Check the rule while the split is being built, so a bad choice is dropped at once. The state is a pattern index i and a position j in s. If pattern[i] already has a piece, that piece must appear in s at j, and there is nothing to choose: jump over it. If the letter is new, try every piece s[j..end) that no other letter owns yet, record it in the map and in the used set, recurse, and undo both records if the rest fails. Success means the pattern and s run out at the same moment.
- match(i, j): if i == pattern.length, return j == s.length.
- Letter c = pattern[i] already mapped to w: if s does not continue with w at j, return false; else return match(i + 1, j + w.length).
- New letter: for every end from j + 1 to s.length, skip the piece if it is used; otherwise map c to it, mark it used, and return true if match(i + 1, end) succeeds.
- Undo the map entry and the used mark, try the next end, and return false when none works.
class Solution {
public boolean wordPatternMatch(String pattern, String s) {
return match(pattern, 0, s, 0, new HashMap<>(), new HashSet<>());
}
private boolean match(String pattern, int i, String s, int j,
Map<Character, String> toPiece, Set<String> used) {
if (i == pattern.length()) return j == s.length();
char c = pattern.charAt(i);
String w = toPiece.get(c);
if (w != null) {
if (!s.startsWith(w, j)) return false;
return match(pattern, i + 1, s, j + w.length(), toPiece, used);
}
for (int end = j + 1; end <= s.length(); end++) {
String piece = s.substring(j, end);
if (used.contains(piece)) continue;
toPiece.put(c, piece);
used.add(piece);
if (match(pattern, i + 1, s, end, toPiece, used)) return true;
toPiece.remove(c);
used.remove(piece);
}
return false;
}
}class Solution:
def wordPatternMatch(self, pattern: str, s: str) -> bool:
return self.match(pattern, 0, s, 0, {}, set())
def match(self, pattern: str, i: int, s: str, j: int, to_piece: dict, used: set) -> bool:
if i == len(pattern):
return j == len(s)
c = pattern[i]
w = to_piece.get(c)
if w is not None:
if not s.startswith(w, j):
return False
return self.match(pattern, i + 1, s, j + len(w), to_piece, used)
for end in range(j + 1, len(s) + 1):
piece = s[j:end]
if piece in used:
continue
to_piece[c] = piece
used.add(piece)
if self.match(pattern, i + 1, s, end, to_piece, used):
return True
del to_piece[c]
used.remove(piece)
return Falseclass Solution {
public:
bool wordPatternMatch(string pattern, string s) {
unordered_map<char, string> toPiece;
unordered_set<string> used;
return match(pattern, 0, s, 0, toPiece, used);
}
private:
bool match(const string& pattern, int i, const string& s, int j,
unordered_map<char, string>& toPiece, unordered_set<string>& used) {
if (i == (int) pattern.size()) return j == (int) s.size();
char c = pattern[i];
auto it = toPiece.find(c);
if (it != toPiece.end()) {
const string w = it->second;
if (s.compare(j, w.size(), w) != 0) return false;
return match(pattern, i + 1, s, j + w.size(), toPiece, used);
}
for (int end = j + 1; end <= (int) s.size(); end++) {
string piece = s.substr(j, end - j);
if (used.count(piece)) continue;
toPiece[c] = piece;
used.insert(piece);
if (match(pattern, i + 1, s, end, toPiece, used)) return true;
toPiece.erase(c);
used.erase(piece);
}
return false;
}
};function wordPatternMatch(pattern, s) {
return match(pattern, 0, s, 0, new Map(), new Set());
}
function match(pattern, i, s, j, toPiece, used) {
if (i === pattern.length) return j === s.length;
const c = pattern[i];
const w = toPiece.get(c);
if (w !== undefined) {
if (!s.startsWith(w, j)) return false;
return match(pattern, i + 1, s, j + w.length, toPiece, used);
}
for (let end = j + 1; end <= s.length; end++) {
const piece = s.substring(j, end);
if (used.has(piece)) continue;
toPiece.set(c, piece);
used.add(piece);
if (match(pattern, i + 1, s, end, toPiece, used)) return true;
toPiece.delete(c);
used.delete(piece);
}
return false;
}3Optimal (backtracking with length pruning)
O(n^m)The worst case is the same as plain backtracking, but every new letter now tries at most n - j - (letters left) lengths, and calls that cannot fit the remaining letters return immediately.O(m + n)Recursion depth at most m, plus the map and set holding pieces of total length at most n.Same search, plus one cheap test that removes hopeless branches. Every pattern letter still to come needs at least one character of s. So when pattern[i] is new, its piece can end no later than s.length minus the number of letters after it, and if fewer characters remain than letters, the call fails at once. In the worst case the search is still exponential, but most dead ends now stop before they start.
- match(i, j): if i == pattern.length, return j == s.length. If s.length - j < pattern.length - i, return false.
- Letter already mapped to w: s must continue with w at j; recurse with i + 1 and j + w.length.
- New letter: let last = s.length - (pattern.length - i - 1). Try every end from j + 1 to last whose piece is unused: map it, mark it, recurse, undo.
- Return false when no choice works.
class Solution {
public boolean wordPatternMatch(String pattern, String s) {
return match(pattern, 0, s, 0, new HashMap<>(), new HashSet<>());
}
private boolean match(String pattern, int i, String s, int j,
Map<Character, String> toPiece, Set<String> used) {
if (i == pattern.length()) return j == s.length();
if (s.length() - j < pattern.length() - i) return false;
char c = pattern.charAt(i);
String w = toPiece.get(c);
if (w != null) {
if (!s.startsWith(w, j)) return false;
return match(pattern, i + 1, s, j + w.length(), toPiece, used);
}
int last = s.length() - (pattern.length() - i - 1);
for (int end = j + 1; end <= last; end++) {
String piece = s.substring(j, end);
if (used.contains(piece)) continue;
toPiece.put(c, piece);
used.add(piece);
if (match(pattern, i + 1, s, end, toPiece, used)) return true;
toPiece.remove(c);
used.remove(piece);
}
return false;
}
}class Solution:
def wordPatternMatch(self, pattern: str, s: str) -> bool:
return self.match(pattern, 0, s, 0, {}, set())
def match(self, pattern: str, i: int, s: str, j: int, to_piece: dict, used: set) -> bool:
if i == len(pattern):
return j == len(s)
if len(s) - j < len(pattern) - i:
return False
c = pattern[i]
w = to_piece.get(c)
if w is not None:
if not s.startswith(w, j):
return False
return self.match(pattern, i + 1, s, j + len(w), to_piece, used)
last = len(s) - (len(pattern) - i - 1)
for end in range(j + 1, last + 1):
piece = s[j:end]
if piece in used:
continue
to_piece[c] = piece
used.add(piece)
if self.match(pattern, i + 1, s, end, to_piece, used):
return True
del to_piece[c]
used.remove(piece)
return Falseclass Solution {
public:
bool wordPatternMatch(string pattern, string s) {
unordered_map<char, string> toPiece;
unordered_set<string> used;
return match(pattern, 0, s, 0, toPiece, used);
}
private:
bool match(const string& pattern, int i, const string& s, int j,
unordered_map<char, string>& toPiece, unordered_set<string>& used) {
int m = pattern.size(), n = s.size();
if (i == m) return j == n;
if (n - j < m - i) return false;
char c = pattern[i];
auto it = toPiece.find(c);
if (it != toPiece.end()) {
const string w = it->second;
if (s.compare(j, w.size(), w) != 0) return false;
return match(pattern, i + 1, s, j + w.size(), toPiece, used);
}
int last = n - (m - i - 1);
for (int end = j + 1; end <= last; end++) {
string piece = s.substr(j, end - j);
if (used.count(piece)) continue;
toPiece[c] = piece;
used.insert(piece);
if (match(pattern, i + 1, s, end, toPiece, used)) return true;
toPiece.erase(c);
used.erase(piece);
}
return false;
}
};function wordPatternMatch(pattern, s) {
return match(pattern, 0, s, 0, new Map(), new Set());
}
function match(pattern, i, s, j, toPiece, used) {
if (i === pattern.length) return j === s.length;
if (s.length - j < pattern.length - i) return false;
const c = pattern[i];
const w = toPiece.get(c);
if (w !== undefined) {
if (!s.startsWith(w, j)) return false;
return match(pattern, i + 1, s, j + w.length, toPiece, used);
}
const last = s.length - (pattern.length - i - 1);
for (let end = j + 1; end <= last; end++) {
const piece = s.substring(j, end);
if (used.has(piece)) continue;
toPiece.set(c, piece);
used.add(piece);
if (match(pattern, i + 1, s, end, toPiece, used)) return true;
toPiece.delete(c);
used.delete(piece);
}
return false;
}Edge cases to test
- The pattern is longer than s: every letter needs at least one character, so the answer is false
- Two different letters wanting the same piece: the mapping must be one-to-one, not just a function
- One letter repeated (
"aaa"): s must be the same piece written that many times - Every letter different: any split into distinct pieces works, so the pieces must all differ
- A pattern of one letter always matches, because that letter can stand for the whole of s
- A letter may stand for a piece that happens to be its own name, such as a for "a"
Hints
Hint 1
If you knew where each piece of s ends, checking the rule would be easy: walk the pattern and keep a map in each direction.
Hint 2
Build the split from the left. At pattern letter i and position j in s, a letter that already has a piece must find exactly that piece at j; a new letter can try every piece that starts at j.
Hint 3
A new letter may not take a piece that another letter already owns. Keep the owned pieces in a set, and undo both the map entry and the set entry when you backtrack.
Hint 4
Each of the remaining pattern letters needs at least one character, so a new piece can end no later than s.length - (letters left after this one).
FAQ
What is the best time complexity for Word Pattern II?
Optimal (backtracking with length pruning) runs in O(n^m) time and O(m + n) extra space. The worst case is the same as plain backtracking, but every new letter now tries at most n - j - (letters left) lengths, and calls that cannot fit the remaining letters return immediately.
Which pattern does Word Pattern II use?
It is a recursion & backtracking problem that uses the choice per position pattern. Other problems with the same pattern: Letter Combinations of a Phone Number, Confusing Number II, Strobogrammatic Number II.
Is there a brute force solution for Word Pattern II?
Yes. Brute force (try every split) takes O(C(n - 1, m - 1) * n) time and O(n) space. Every candidate answer is a way to cut s into exactly pattern.length non-empty pieces.
Which edge cases should I test for Word Pattern II?
The pattern is longer than s: every letter needs at least one character, so the answer is false; Two different letters wanting the same piece: the mapping must be one-to-one, not just a function; One letter repeated ("aaa"): s must be the same piece written that many times; Every letter different: any split into distinct pieces works, so the pieces must all differ; A pattern of one letter always matches, because that letter can stand for the whole of s; A letter may stand for a piece that happens to be its own name, such as a for "a".