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.