Practice
from collections import deque
def first_unique_stream(stream):
freq = [0] * 26
q = deque()
result = []
for ch in stream:
idx = ord(ch) - ord('a')
freq[idx] += 1
if freq[idx] == 1:
q.append(ch)
while q and freq[ord(q[0]) - ord('a')] > 1:
q.popleft()
result.append(q[0] if q else '#')
return result
print(first_unique_stream(['a', 'b', 'a']))
Solution
Step 1: Trace first iteration with 'a'
freq['a'] = 1, queue = ['a'], first unique = 'a'Step 2: Trace second iteration with 'b'
freq['b'] = 1, queue = ['a', 'b'], first unique still 'a' since freq['a'] = 1Step 3: Trace third iteration with 'a'
freq['a'] = 2, queue front 'a' freq > 1, pop 'a', queue now ['b'], first unique = 'b'Final Answer:
Option A -> Option AQuick Check:
Queue updates correctly remove duplicates [OK]
- Not popping duplicates from queue front
- Appending duplicates to queue multiple times
- Returning wrong character after duplicates
[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
def calculate(s: str) -> int:
stack = []
result = 0
sign = 1
num = 0
for i, c in enumerate(s):
if c.isdigit():
num = int(c) # Bug here
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: Analyze digit processing
Bug is in 'num = int(c)' which resets num instead of accumulating digits for multi-digit numbers.Step 2: Effect of bug
Multi-digit numbers are treated as single digits, causing incorrect calculation.Final Answer:
Option B -> Option BQuick Check:
Correct code uses 'num = num * 10 + int(c)' [OK]
- Resetting num instead of accumulating digits
Solution
Step 1: Examine tail pointer update
Tail pointer increments by 1 but lacks modulo operation, so it can exceed array bounds.Step 2: Understand consequences
Without modulo, tail pointer goes out of range causing runtime errors or incorrect behavior.Final Answer:
Option A -> Option AQuick Check:
Modulo operation is essential for circular wrap-around [OK]
- Forgetting modulo wrap-around
- Using size incorrectly to check full
- Misordering size increment
Solution
Step 1: Understand wildcard impact
Wildcards can represent multiple bracket types or empty, so a single stack is insufficient to track all possibilities.Step 2: Use two stacks approach
One stack tracks positions of opening brackets, another tracks positions of '*'. This allows matching '*' as needed to balance brackets efficiently in one pass.Step 3: Reject invalid sequences
After processing, ensure all unmatched opening brackets can be matched by '*' positions appearing after them.Final Answer:
Option C -> Option CQuick Check:
Two stacks track brackets and wildcards to handle all cases [OK]
- Replacing '*' blindly or ignoring them causes incorrect results
