Question Bank
Stack and Queue Fundamentals
Difficulty: Easy
Four short prompts on LIFO vs FIFO behavior, balanced parentheses, and a bug hunt in a circular queue. Good warm-up before monotonic-stack drills.
Stack and Queue Fundamentals
Four short prompts on LIFO vs FIFO behavior, balanced parentheses, and a bug hunt in a circular queue. Good warm-up before monotonic-stack drills.
957 views
8
What does this snippet print and why? Identify which structure is LIFO and which is FIFO.
Examples
Example 1:
Input: push 1, 2, 3 then pop twice on a stack; push 1, 2, 3 then shift twice on a queue
Output: stack pops 3, 2 (LIFO); queue shifts 1, 2 (FIFO)
Explanation: Stacks return the most recently pushed element. Queues return the oldest. Note Array.prototype.shift is O(n); use a deque or head-index for true O(1) FIFO.Implement isBalanced(s) that returns true if the parentheses, brackets, and braces in s are balanced. Use a stack.
Examples
Example 1:
Input: s = '([{}])'
Output: true
Explanation: For each opener, push the matching closer. For each closer, fail if stack empty or top mismatches. The final stack is empty, so balanced.Example 2:
Input: s = '([)]'
Output: false
Explanation: After pushing ')', ']', the next character is ')' but the top is ']', mismatch, return false.Implement a Queue using two stacks. Support enqueue(x) and dequeue() with amortized O(1) per operation.
Examples
Example 1:
Input: enqueue(1); enqueue(2); enqueue(3); then dequeue() twice
Output: first dequeue returns 1; second returns 2
Explanation: enqueue pushes to in. dequeue pops from out; if out is empty, drain in into out (reversing the order). Each element is moved at most once, giving amortized O(1).Spot the bug. This circular queue's enqueue allows overwrites without flagging the queue as full.
Examples
Example 1:
Input: capacity = 2; enqueue(1); enqueue(2); enqueue(3)
Output (buggy version): size corrupts past cap and slot 0 is overwritten
Output (fixed version): third enqueue returns false and the queue is unchanged
Explanation: There is no full check, so callers can overwrite live data when size === cap. The fix returns false (or throws) when the queue is full and only writes / advances on success.