Word Pattern
Solve this ProblemTest Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ pattern.length ≤ 10 - ◆
pattern consists of lowercase English letters - ◆
s consists of lowercase English letters and single spaces, with no leading or trailing spaces - ◆
1 ≤ number of words in s ≤ 10
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Parallel Arrays, Linear Lookup
GoodSplit s into words. Instead of a hash map, keep two plain lists — one of characters seen so far, one of the words they were paired with — in the same order. For each pattern character and word, scan the lists to see if either has already been paired with something else, and reject if so; otherwise, if neither has been seen, append the new pair. It's a direct simulation of "have I paired this before?", but every check re-scans the lists from the start, so the work grows with the square of the pattern length.
O(n²)O(n)1class Solution {
2 public boolean wordPattern(String pattern, String s) {
3 String[] words = s.split(" ");
4 if (pattern.length() != words.length) return false;
5 List<Character> mappedChars = new ArrayList<>();
6 List<String> mappedWords = new ArrayList<>();
7 for (int i = 0; i < pattern.length(); i++) {
8 char c = pattern.charAt(i);
9 String w = words[i];
10 int charSeenAt = mappedChars.indexOf(c);
11 int wordSeenAt = mappedWords.indexOf(w);
12 if (charSeenAt != -1 && !mappedWords.get(charSeenAt).equals(w)) return false;
13 if (wordSeenAt != -1 && mappedChars.get(wordSeenAt) != c) return false;
14 if (charSeenAt == -1 && wordSeenAt == -1) {
15 mappedChars.add(c);
16 mappedWords.add(w);
17 }
18 }
19 return true;
20 }
21}Optimal — Two HashMaps, Single Pass
OptimalA valid pattern needs a two-way (bijective) mapping, so track both directions at once with two hash maps: charToWord and wordToChar. Walk the pattern and words together; if the current character is already mapped to a different word, or the current word is already mapped to a different character, the pattern breaks — reject immediately. Otherwise record both mappings and continue. Every check is an O(1) hash map lookup, so the whole pass is linear.
O(n)O(n)1class Solution {
2 public boolean wordPattern(String pattern, String s) {
3 String[] words = s.split(" ");
4 if (pattern.length() != words.length) return false;
5 Map<Character, String> charToWord = new HashMap<>();
6 Map<String, Character> wordToChar = new HashMap<>();
7 for (int i = 0; i < pattern.length(); i++) {
8 char c = pattern.charAt(i);
9 String w = words[i];
10 if (charToWord.containsKey(c) && !charToWord.get(c).equals(w)) return false;
11 if (wordToChar.containsKey(w) && wordToChar.get(w) != c) return false;
12 charToWord.put(c, w);
13 wordToChar.put(w, c);
14 }
15 return true;
16 }
17}