Practice
q = MyQueue()
q.push(10)
q.push(20)
print(q.pop())
q.push(30)
print(q.peek())
Solution
Step 1: Trace pop() after pushing 10 and 20
pop_stack is empty, transfer push_stack [10,20] reversed to pop_stack [20,10], pop() returns 10.Step 2: After pushing 30, peek() checks pop_stack which has [20], so peek returns 20
After pop(), pop_stack has [20], push_stack has [30]. peek() does not transfer because pop_stack is not empty, so peek returns 20.Final Answer:
Option B -> Option BQuick Check:
pop() returns 10, peek() returns 20 [OK]
- Assuming peek returns 10 after pop
- Forgetting transfer only when pop_stack empty
nextGreaterElement([4,1,2], [1,3,4,2])?Solution
Step 1: Trace stack and map updates for nums2
Process nums2: push 1, then 3 > 1 so pop 1 -> map[1]=3; push 3; 4 > 3 pop 3 -> map[3]=4; push 4; 2 < 4 push 2. Stack ends with [4,2].Step 2: Assign -1 for remaining stack elements and build result
Pop 2 -> map[2]=-1; pop 4 -> map[4]=-1. Result for nums1=[4,1,2] is [map[4], map[1], map[2]] = [-1,3,-1].Final Answer:
Option B -> Option BQuick Check:
Matches expected output from code comments and manual trace [OK]
- Confusing order of popping leading to wrong map values
- Forgetting to assign -1 for elements with no next greater
- Mixing up indices when building the final result
Solution
Step 1: Identify where repeat count is reset
After pushing k to count_stack on '[', k must be reset to 0 to avoid carryover to next substring.Step 2: Locate missing reset
The code comment indicates missing reset of k after pushing it, causing subsequent repeats to accumulate incorrectly.Final Answer:
Option C -> Option CQuick Check:
Resetting k prevents repeat count carryover bugs [OK]
- Forgetting to reset repeat count after '['
- Mismanaging stack push/pop order
def pop(self) -> int:
while self.push_stack:
self.pop_stack.append(self.push_stack.pop())
return self.pop_stack.pop()
Solution
Step 1: Identify transfer condition
The code transfers elements from push_stack to pop_stack on every pop, regardless of pop_stack state.Step 2: Understand impact
This causes O(n) time on every pop, losing amortized O(1) efficiency.Final Answer:
Option C -> Option CQuick Check:
Transfer only when pop_stack empty -> amortized O(1) [OK]
- Transferring every pop causes O(n) pop time
- Not checking empty queue before pop
Solution
Step 1: Analyze push and pop operations
Each digit is pushed exactly once onto the stack. Each digit can be popped at most once when a smaller digit arrives.Step 2: Conclude overall complexity
Since each digit is pushed and popped at most once, total operations are O(n), linear in input size.Final Answer:
Option B -> Option BQuick Check:
Monotonic stack ensures linear time by amortized analysis [OK]
- Assuming worst case k pops per digit -> O(n*k)
- Thinking sorting or nested loops are involved
