Skip to main content
Back to problems
#290
Easy Algorithms

Word pattern

Hash Table String
43.8% acceptance
Jan 12, 2026
7947
1140
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. Specifically: Each letter in pattern maps to exactly one unique word in s. Each unique word in s maps to exactly one letter in pattern. No two letters map to the same word, and no two words map to the same letter.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn word_pattern(pattern: String, s: String) -> bool {
    use std::collections::HashMap;
    let words: Vec<&str> = s.split_whitespace().collect();
    let pattern_chars: Vec<char> = pattern.chars().collect();
    
    if pattern_chars.len() != words.len() {
      return false;
    }
    
    let mut char_to_word = HashMap::new();
    let mut word_to_char = HashMap::new();
    
    for (ch, word) in pattern_chars.iter().zip(words.iter()) {
      if let Some(&mapped_word) = char_to_word.get(ch) {
        if mapped_word != *word {
          return false;
        }
      } else {
        char_to_word.insert(*ch, *word);
      }
      
      if let Some(&mapped_char) = word_to_char.get(word) {
        if mapped_char != *ch {
          return false;
        }
      } else {
        word_to_char.insert(*word, *ch);
      }
    }
    
    true
  }
}