EasyNo. 0290

Word Pattern — LeetCode 290 Python Solution

Pattern
Hash Map
Topics
Hash Table, String
On a study list
Top Interview 150
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

PythonSolution
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

Time
O(m + n)
Space · auxiliary
O(m + n)

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

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.

Free to download. Check it runs on your machine, then pick a plan.