Practice
"3+2*2"?Solution
Step 1: Trace first number and operator
Read '3', current_op='+', total=0, last_num=0. On '+', total += last_num (0), last_num=3.Step 2: Process '2*2'
Read '2', operator '*', current_op='+', so total += last_num (3), last_num=2. Then read '2' after '*', current_op='*', last_num=2*2=4.Step 3: End of string
Add last_num (4) to total (3), total=7.Final Answer:
Option D -> Option DQuick Check:
3 + (2*2) = 7 matches traced total [OK]
- Adding numbers before multiplication
- Off-by-one in loop end
- Not adding last_num at end
result immediately after processing the character ')' at index 6 in the input string "(1+(2-3))"?
def calculate(s: str) -> int:
stack = []
result = 0
sign = 1
num = 0
for i, c in enumerate(s):
if c.isdigit():
num = num * 10 + int(c)
elif c in '+-':
result += sign * num
num = 0
sign = 1 if c == '+' else -1
elif c == '(': # Push current result and sign
stack.append(result)
stack.append(sign)
result = 0
sign = 1
elif c == ')': # Add last number and combine
result += sign * num
num = 0
result *= stack.pop()
result += stack.pop()
result += sign * num
return result
Solution
Step 1: Trace characters up to index 6
Input: "(1+(2-3))" - i=0:'(' push 0 and 1, result=0, sign=1 - i=1:'1' num=1 - i=2:'+' result=0+1*1=1, num=0, sign=1 - i=3:'(' push 1 and 1, result=0, sign=1 - i=4:'2' num=2 - i=5:'-' result=0+1*2=2, num=0, sign=-1 - i=6:'3' num=3Step 2: Process character at index 6 (')')
At ')': result += sign*num = 2 + (-1)*3 = -1 num=0 result *= stack.pop() -> result *= 1 -> -1 result += stack.pop() -> -1 + 1 = 0Final Answer:
Option A -> Option AQuick Check:
Result after popping stack is 0 [OK]
- Forgetting to add last number before popping stack
3[a2[c]], where numbers indicate how many times the substring inside brackets should be repeated. Which algorithmic approach guarantees an optimal and correct decoding of such nested patterns?Solution
Step 1: Understand nested pattern decoding
The problem requires handling nested brackets and repeat counts, which demands tracking multiple levels of context.Step 2: Identify approach that handles nesting efficiently
A stack-based iterative approach uses two stacks to store counts and partial decoded strings, correctly managing nested repeats without excessive recursion or incorrect greedy expansions.Final Answer:
Option D -> Option DQuick Check:
Stack approach correctly decodes nested patterns like 3[a2[c]] -> accaccacc [OK]
- Assuming greedy expansion works for nested patterns
- Using recursion without proper state tracking
Solution
Step 1: Understand the problem transformation
The problem can be transformed row-wise into histograms where each element represents the height of consecutive 1s above it.Step 2: Recognize the monotonic stack pattern
For each histogram, the largest rectangle can be found efficiently using a monotonic stack that tracks indices of increasing heights.Final Answer:
Option C -> Option CQuick Check:
Histogram + monotonic stack approach is standard for maximal rectangle [OK]
- Trying brute force leads to O(n^4) time
- Greedy expansion fails on complex shapes
- DP without histogram misses efficient stack usage
[3, 7, 1]?
def previous_smaller_element_indexes(arr):
stack = []
result = []
for i, num in enumerate(arr):
while stack and arr[stack[-1]] >= num:
stack.pop()
if stack:
result.append(arr[stack[-1]])
else:
result.append(-1)
stack.append(i)
return result
print(previous_smaller_element_indexes([3, 7, 1]))
Solution
Step 1: Trace iteration i=0, num=3
Stack empty, append -1 to result, push index 0 -> stack=[0], result=[-1]Step 2: Trace iteration i=1, num=7
Stack top index 0 -> arr[0]=3 < 7, so append 3 to result, push index 1 -> stack=[0,1], result=[-1,3]Step 3: Trace iteration i=2, num=1
Pop while arr[stack[-1]] >= 1: arr[1]=7 >=1 pop, arr[0]=3 >=1 pop, stack empty, append -1, push index 2 -> stack=[2], result=[-1,3,-1]Final Answer:
Option B -> Option BQuick Check:
Output matches expected previous smaller elements for each position [OK]
- Not popping equal or greater elements leads to wrong result
- Appending wrong element from stack top
- Off-by-one errors in indexing
