Word Pattern
LeetCode 290 · आसान · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Last-seen index per letter and per word must agree.
मैंने Word Pattern (LeetCode 290) ऐसे हल किया — Hashing / Frequency पैटर्न का एक आसान प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Same idea as isomorphic strings, but between pattern letters and words: each letter and its word must have been last seen at the same index.
Approach
- 1
Split s into words; lengths must match.
- 2
Compare stored indices for pattern[i] and words[i].
- 3
Record the current index for both.
मैंने कैसे हल किया
Last-seen indicesPythonO(n) time · O(n) space
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
pattern_mpp = {}
s_mpp = {}
words = s.split(" ")
if len(pattern)!=len(words):
return False
for i in range(len(pattern)):
char = pattern[i]
word = words[i]
if pattern_mpp.get(char,-1)!=s_mpp.get(word,-1):
return False
pattern_mpp[char]=i
s_mpp[word]=i
return TrueWord Pattern — अक्सर पूछे जाने वाले प्रश्न
Word Pattern के पीछे intuition क्या है?
Same idea as isomorphic strings, but between pattern letters and words: each letter and its word must have been last seen at the same index.
Word Pattern (LeetCode 290) कैसे हल करें?
1. Split s into words; lengths must match. 2. Compare stored indices for pattern[i] and words[i]. 3. Record the current index for both.
Word Pattern की time और space complexity क्या है?
Time: O(n)। Space: O(n)। (Accepted approach: Last-seen indices।)
Word Pattern में आम गलतियाँ क्या हैं?
Length mismatch is an immediate False.