#290

Word Pattern

Easy
Hash TableStringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

This approach uses two hash maps to create a one-to-one mapping between characters and words efficiently, ensuring we only traverse the input once.

⚙️

Algorithm

3 steps
  1. 1Step 1: Split the string 's' into words.
  2. 2Step 2: Initialize two hash maps: one for character to word mapping and another for word to character mapping.
  3. 3Step 3: Iterate through the pattern and words simultaneously, updating the hash maps and checking for consistency.
solution.py20 lines
1# Full working Python code
2
3def wordPattern(pattern, s):
4    words = s.split()
5    if len(pattern) != len(words):
6        return False
7    char_to_word = {}
8    word_to_char = {}
9    for char, word in zip(pattern, words):
10        if char in char_to_word:
11            if char_to_word[char] != word:
12                return False
13        else:
14            char_to_word[char] = word
15        if word in word_to_char:
16            if word_to_char[word] != char:
17                return False
18        else:
19            word_to_char[word] = char
20    return True

Complexity note: The time complexity is O(n) because we only traverse the pattern and the words once, making it efficient. The space complexity is O(n) due to the storage of mappings in hash maps.

  • 1A bijection means each character must map to a unique word and vice versa.
  • 2The number of unique characters must match the number of unique words.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.