Files
framework_note/leetcode/note/easy/290_word_pattern.md
T
2026-06-05 18:15:42 -04:00

3.0 KiB

id, title, difficulty, tags, status, date_solved, leetcode_url, review_needed
id title difficulty tags status date_solved leetcode_url review_needed
290 Word Pattern Easy
hash-table
string
Solved 2026-06-05 https://leetcode.com/problems/word-pattern/ false

290. Word Pattern

[!info] Problem Link: LeetCode - Word Pattern

📝 Problem Description

Given a pattern and a string s, find if s follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.


📥 Example 1

Input: pattern = "abba", s = "dog cat cat dog" Output: true

📥 Example 2

Input: pattern = "abba", s = "dog cat cat fish" Output: false

📥 Example 3

Input: pattern = "aaaa", s = "dog cat cat dog" Output: false


💡 Approaches & Explanations

Approach 1: Two Hash Maps (Bijective Mapping) — Optimal

To ensure a bijection (one-to-one mapping) between characters in pattern and words in s, we need to verify two things:

  1. Every character in pattern maps to exactly one word in s.
  2. Every word in s maps to exactly one character in pattern.

Using two hash maps allows us to track these mappings in both directions. Alternatively, we can use one hash map for the mapping and a set to ensure the values are unique.

📊 Complexity Analysis

  • Time Complexity: \mathcal{O}(N + M) where N is the number of characters in the pattern and M is the number of characters in string s. We split the string and then iterate through the pattern.
  • Space Complexity: \mathcal{O}(W) where W is the number of unique words in s and unique characters in pattern.

💻 Code Implementations

Python3

class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        words = s.split()
        
        if len(pattern) != len(words):
            return False
            
        char_to_word = {}
        word_to_char = {}
        
        for char, word in zip(pattern, words):
            if char in char_to_word:
                if char_to_word[char] != word:
                    return False
            else:
                char_to_word[char] = word
                
            if word in word_to_char:
                if word_to_char[word] != char:
                    return False
            else:
                word_to_char[word] = char
                
        return True

🧠 Key Takeaways & Lessons

  • Bijective Mapping: When a problem requires a 1-to-1 relationship, remember that a single hash map only tracks the mapping in one direction. You must either use two maps or check that the values in the single map are unique.
  • String Splitting: Python's .split() defaults to splitting by any whitespace, which is perfect for space-separated word problems.
  • Zip for Parallel Iteration: The zip() function is an idiomatic way to iterate over two sequences simultaneously.