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.
Question Bank
Easy
JavaScript
4 questions
stack
queue
data-structures
fundamentals
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.const stack = [];
stack.push(1); stack.push(2); stack.push(3);
console.log(stack.pop(), stack.pop());
const queue = [];
queue.push(1); queue.push(2); queue.push(3);
console.log(queue.shift(), queue.shift());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.function isBalanced(s) {
// TODO: stack of expected closers
}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).class Queue {
// TODO: two stacks (in, out)
}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.class CircularQueue {
constructor(capacity) {
this.buf = new Array(capacity);
this.cap = capacity;
this.head = 0;
this.tail = 0;
this.size = 0;
}
enqueue(x) {
this.buf[this.tail] = x;
this.tail = (this.tail + 1) % this.cap;
this.size++;
}
}