Word Pattern — LeetCode 290 Python Solution

EasyHash TableString
Problem
#290
Pattern
Hash Map
Reading time
2 min

The problem

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.

Python solution

Python
class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        ws = s.split()
        if len(pattern) != len(ws):
            return False
        d1 = {}
        d2 = {}
        for a, b in zip(pattern, ws):
            if (a in d1 and d1[a] != b) or (b in d2 and d2[b] != a):
                return False
            d1[a] = b
            d2[b] = a
        return True

Complexity

MeasureComplexity
TimeO(m + n)
SpaceO(m + n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 290. Word Pattern is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 290. Word Pattern?
LeetCode 290. Word Pattern is rated Easy on LeetCode.
What is the time complexity of LeetCode 290. Word Pattern?
The Python solution on this page runs in O(m + n).
What is the space complexity of LeetCode 290. Word Pattern?
The Python solution on this page uses O(m + n) auxiliary space.
What topics does LeetCode 290. Word Pattern cover?
LeetCode 290. Word Pattern is tagged Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview