Basic Calculator
LeetCode 224 · কঠিন · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Stack saves (answer, sign) at each '('.
আমি Basic Calculator (LeetCode 224) এভাবে সমাধান করেছি — Expression Evaluation প্যাটার্নের একটি কঠিন প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।
নিচের বিবরণ ইংরেজিতে।
Intuition
Without * or /, an expression is just signed numbers added up. Keep a running answer and the current sign. On '(' save the answer and sign so far on a stack and start fresh; on ')' finish the inner value, apply the saved sign, and add the saved answer.
Approach
- 1
Digits → read the full number, add sign × number.
- 2
'+' / '−' set the sign.
- 3
'(' → push ans and sign, reset.
- 4
')' → ans = saved_ans + saved_sign × ans.
আমি কীভাবে সমাধান করেছি
Sign stackPythonO(n) time
class Solution:
def calculate(self, s: str) -> int:
#if it is a number
#calculate number and add to answer with the current sign
#if it's ( - add current answer and sign to the stack
#if it's ) - take last sign, last total and apply to the ans
#if it's - - sign =-1
#if it's + sign=1
i=0
ans = 0
sign = 1
stack = []
while i<len(s):
if s[i].isdigit():
num = 0
#"123"
while i<len(s) and s[i].isdigit():
num = num*10+int(s[i])
i+=1
ans+=num*sign
i-=1 #we incremented extra
elif s[i]=="+":
sign = 1
elif s[i]=="-":
sign =-1
elif s[i]=="(":
stack.append(ans)
stack.append(sign)
#reset
ans=0
sign = 1
elif s[i]==")":
last_sign = stack.pop()
last_total=stack.pop()
ans = ans*last_sign
ans+=last_total
i+=1
return ansBasic Calculator — সাধারণ প্রশ্ন
Basic Calculator-এর পেছনে intuition কী?
Without * or /, an expression is just signed numbers added up. Keep a running answer and the current sign. On '(' save the answer and sign so far on a stack and start fresh; on ')' finish the inner value, apply the saved sign, and add the saved answer.
Basic Calculator (LeetCode 224) কীভাবে সমাধান করবেন?
1. Digits → read the full number, add sign × number. 2. '+' / '−' set the sign. 3. '(' → push ans and sign, reset. 4. ')' → ans = saved_ans + saved_sign × ans.
Basic Calculator-এর time আর space complexity কত?
Time: O(n)। Space: O(n)। (Accepted approach: Sign stack।)
Basic Calculator-এ সাধারণ ভুলগুলো কী?
Step back one index after reading a multi-digit number.