Valid Parentheses
LeetCode 20 · आसान · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Push openers; each closer must match the top.
मैंने Valid Parentheses (LeetCode 20) ऐसे हल किया — Parentheses / Bracket Matching पैटर्न का एक आसान प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Every closing bracket must match the most recent unmatched opening bracket — that's last-in-first-out, a stack.
Approach
- 1
Opening bracket → push.
- 2
Closing bracket → pop and check it matches; empty stack → invalid.
- 3
Valid only if the stack is empty at the end.
मैंने कैसे हल किया
Stack matchingPythonO(n) time · O(n) space
class Solution:
def isValid(self, s: str) -> bool:
stack = []
mpp={
"(":")",
"{":"}",
"[":"]"
}
stack = []
for char in s:
if char in mpp:
stack.append(char)
else:
closing_brace = char
if stack:
opening_brace = stack.pop()
if mpp[opening_brace]!=closing_brace:
return False
else:
return False
return True if len(stack)==0 else FalseValid Parentheses — अक्सर पूछे जाने वाले प्रश्न
Valid Parentheses के पीछे intuition क्या है?
Every closing bracket must match the most recent unmatched opening bracket — that's last-in-first-out, a stack.
Valid Parentheses (LeetCode 20) कैसे हल करें?
1. Opening bracket → push. 2. Closing bracket → pop and check it matches; empty stack → invalid. 3. Valid only if the stack is empty at the end.
Valid Parentheses की time और space complexity क्या है?
Time: O(n)। Space: O(n)। (Accepted approach: Stack matching।)
Valid Parentheses में आम गलतियाँ क्या हैं?
Leftover openers like '((' make it invalid.