Valid Parenthesis String
LeetCode 678 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Two counters: optimistic opens forward, optimistic closes backward.
আমি Valid Parenthesis String (LeetCode 678) এভাবে সমাধান করেছি — Parentheses / Bracket Matching প্যাটার্নের একটি মাঝারি প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।
নিচের বিবরণ ইংরেজিতে।
Intuition
Scan left to right treating every '*' as '(' — if the open count ever goes negative, there are too many ')'. Scan right to left treating every '*' as ')' — if that count goes negative, there are too many '('. Passing both means some assignment works.
Approach
- 1
openCount: +1 for '(' or '*', −1 for ')'.
- 2
closeCount (from the right): +1 for ')' or '*', −1 for '('.
- 3
Either negative → False.
- 4
Earlier version: two stacks of indices.
আমি কীভাবে সমাধান করেছি
Two-direction countingPythonO(n) time · O(1) space
class Solution:
def checkValidString(self, s):
openCount = 0
closeCount = 0
n = len(s)
for i in range(n):
if s[i] == "(" or s[i] == "*":
openCount += 1
else:
openCount -= 1
if s[n - i - 1] == ")" or s[n - i - 1] == "*":
closeCount += 1
else:
closeCount -= 1
if openCount < 0 or closeCount < 0:
return False
return TrueValid Parenthesis String — সাধারণ প্রশ্ন
Valid Parenthesis String-এর পেছনে intuition কী?
Scan left to right treating every '*' as '(' — if the open count ever goes negative, there are too many ')'. Scan right to left treating every '*' as ')' — if that count goes negative, there are too many '('. Passing both means some assignment works.
Valid Parenthesis String (LeetCode 678) কীভাবে সমাধান করবেন?
1. openCount: +1 for '(' or '*', −1 for ')'. 2. closeCount (from the right): +1 for ')' or '*', −1 for '('. 3. Either negative → False. 4. Earlier version: two stacks of indices.
Valid Parenthesis String-এর time আর space complexity কত?
Time: O(n)। Space: O(1)। (Accepted approach: Two-direction counting।)
Valid Parenthesis String-এ সাধারণ ভুলগুলো কী?
A '*' before a '(' can't close it — the stack version checks index order.