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
- Source
- leetcode.com
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
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 TrueComplexity
- 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
| No. | Problem | Difficulty |
|---|---|---|
| 0299 | Bulls and Cows | Medium |
| 0003 | Longest Substring Without Repeating Characters | Medium |
| 0012 | Integer to Roman | Medium |
| 0013 | Roman to Integer | Easy |
| 0017 | Letter Combinations of a Phone Number | Medium |
| 0030 | Substring with Concatenation of All Words | Hard |
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.