easy Word Pattern
Problem Statement
Given a pattern and a string s, return true if the string s follows the same pattern.
Here, the following the pattern means each character in the pattern should map to a single word in s, and each word in s should map to a single character in the pattern.
Examples
Example 1:
- Input: pattern =
"eegg", s ="dog dog cat cat" - Output:
true - Explanation: The pattern "eegg" corresponds to the words "dog dog cat cat". Both 'e's map to "dog" and both 'g's map to "cat".
Example 2:
- Input: pattern =
"abca", s ="one two three four" - Output:
false - Explanation: Here,
amaps to the"one"and"four"both. So, the string doesn't follow the same pattern.
Example 3:
- Input: pattern =
"abacac", s ="dog cat dog mouse dog mouse" - Output:
true - Explanation: The pattern "abacac" corresponds to the words "dog cat dog mouse dog mouse". 'a' maps to "dog", 'b' maps to "cat", and 'c' maps to "mouse".
Constraints:
- 1 <= pattern.length <= 300
- pattern contains only lower-case English letters.
- 1 <= s.length <= 3000
scontains only lowercase English letters and spaces ' '.sdoes not contain any leading or trailing spaces.- All the words in s are separated by a single space.
Try it yourself
Try solving this question here:
✅ Solution Word Pattern
Problem Statement
Given a pattern and a string s, return true if the string s follows the same pattern.
Here, the following the pattern means each character in the pattern should map to a single word in s, and each word in s should map to a single character in the pattern.
Examples
Example 1:
- Input: pattern =
"eegg", s ="dog dog cat cat" - Output:
true - Explanation: The pattern "eegg" corresponds to the words "dog dog cat cat". Both 'e's map to "dog" and both 'g's map to "cat".
Example 2:
- Input: pattern =
"abca", s ="one two three four" - Output:
false - Explanation: Here,
amaps to the"one"and"four"both. So, the string doesn't follow the same pattern.
Example 3:
- Input: pattern =
"abacac", s ="dog cat dog mouse dog mouse" - Output:
true - Explanation: The pattern "abacac" corresponds to the words "dog cat dog mouse dog mouse". 'a' maps to "dog", 'b' maps to "cat", and 'c' maps to "mouse".
Constraints:
- 1 <= pattern.length <= 300
- pattern contains only lower-case English letters.
- 1 <= s.length <= 3000
scontains only lowercase English letters and spaces ' '.sdoes not contain any leading or trailing spaces.- All the words in s are separated by a single space.
Solution
To solve this problem, we need to establish a one-to-one correspondence between each character in the pattern and each word in the string s. This can be effectively managed using two hash maps: one to map characters from the pattern to words in s, and another to map words in s to characters in the pattern. This dual mapping ensures that the relationship is consistent in both directions. If at any point we find that a character or word does not map as expected, we can conclude that string does not follow the pattern.
This approach is efficient because it allows us to quickly check and establish the required mappings. The use of hash maps ensures that our checks and insertions are done in constant time on average, making the overall approach fast and reliable.
Step-by-step Algorithm
- Split the string s into an array of words.
- Check if the length of the pattern matches the number of words in s. If not, return false.
- Initialize two hash maps: one for pattern to word mapping (
char_to_word), and one for word to pattern mapping (word_to_char). - Iterate over each character in the pattern and the corresponding word in s:
- Check if the character is already mapped:
- If it is, ensure it maps to the current word.
- If it does not match, return false.
- Else, add character and word to 'char_to_word' map.
- Check if the word is already mapped:
- If it is, ensure it maps to the current character.
- If it does not match, return false.
- Else, add word and character to 'word_to_char' map.
- Check if the character is already mapped:
- Return true if all characters and words map correctly.
Algorithm Walkthrough
Input: pattern = "abacac", s = "dog cat dog mouse dog mouse"
-
Initial Input:
- Pattern:
abacac - String s:
dog cat dog mouse dog mouse
- Pattern:
-
Step 1: Split the string s into words:
- Words:
["dog", "cat", "dog", "mouse", "dog", "mouse"]
- Words:
-
Step 2: Check length:
- Length of pattern: 6
- Number of words: 6
- Lengths match, proceed to the next step.
-
Step 3: Initialize hash maps:
charToWord = {}wordToChar = {}
-
Step 4: Iterate over each character and word:
-
Iteration 1:
- Character:
a - Word:
dog ais not incharToWord, anddogis not inwordToChar.- Map
atodog:charToWord = {'a': 'dog'} - Map
dogtoa:wordToChar = {'dog': 'a'}
- Character:
-
Iteration 2:
- Character:
b - Word:
cat bis not incharToWord, andcatis not inwordToChar.- Map
btocat:charToWord = {'a': 'dog', 'b': 'cat'} - Map
cattob:wordToChar = {'dog': 'a', 'cat': 'b'}
- Character:
-
Iteration 3:
- Character:
a - Word:
dog ais incharToWord, and it maps todog.dogis inwordToChar, and it maps toa.- Mappings are consistent, proceed to the next iteration.
- Character:
-
Iteration 4:
- Character:
c - Word:
mouse cis not incharToWord, andmouseis not inwordToChar.- Map
ctomouse:charToWord = {'a': 'dog', 'b': 'cat', 'c': 'mouse'} - Map
mousetoc:wordToChar = {'dog': 'a', 'cat': 'b', 'mouse': 'c'}
- Character:
-
Iteration 5:
- Character:
a - Word:
dog ais incharToWord, and it maps todog.dogis inwordToChar, and it maps toa.- Mappings are consistent, proceed to the next iteration.
- Character:
-
Iteration 6:
- Character:
c - Word:
mouse cis incharToWord, and it maps tomouse.mouseis inwordToChar, and it maps toc.- Mappings are consistent.
- Character:
-
-
Step 5: All characters and words are mapped correctly.
- Return
true.
- Return
Code
import java.util.HashMap;
class Solution {
public boolean wordPattern(String pattern, String s) {
// Split the string s into words
String[] words = s.split(" ");
// If lengths of pattern and words do not match, return false
if (pattern.length() != words.length) {
return false;
}
// Initialize hash maps to keep track of mappings
HashMap<Character, String> charToWord = new HashMap<>();
HashMap<String, Character> wordToChar = new HashMap<>();
// Iterate over each character and word
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
String word = words[i];
// Check if the character is already mapped
if (charToWord.containsKey(c)) {
// If mapped word doesn't match the current word, return false
if (!charToWord.get(c).equals(word)) {
return false;
}
} else {
// Map the character to the word
charToWord.put(c, word);
}
// Check if the word is already mapped
if (wordToChar.containsKey(word)) {
// If mapped character doesn't match the current character, return false
if (wordToChar.get(word) != c) {
return false;
}
} else {
// Map the word to the character
wordToChar.put(word, c);
}
}
// If all checks pass, return true
return true;
}
public static void main(String[] args) {
Solution solution = new Solution();
// Example 1
System.out.println(solution.wordPattern("eegg", "dog dog cat cat")); // true
// Example 2
System.out.println(solution.wordPattern("abca", "one two three four")); // false
// Example 3
System.out.println(
solution.wordPattern("abacac", "dog cat dog mouse dog mouse")
); // true
}
}
Complexity Analysis
- Time Complexity:
, where n is the length of the pattern or the number of words in s. We iterate through the pattern and the words once, performing constant-time operations (hash map lookups and insertions) at each step. - Space Complexity:
, where n is the number of unique characters in the pattern or unique words in s. In the worst case, we store every character and word in the hash maps.
🤖 Don't fully get this? Learn it with Claude
Stuck on Word Pattern? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Word Pattern** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Word Pattern** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Word Pattern**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Word Pattern**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.