You have a list of tasks that must be processed in the exact order they arrive. Which data structure is best to use?
Think about which data structure follows the 'first come, first served' rule.
A queue processes elements in the order they arrive (FIFO), which is perfect for task scheduling where order matters. A stack processes elements in reverse order (LIFO), which is not suitable here.
What is the printed output after running this TypeScript code that uses a stack?
class Stack<T> { private items: T[] = []; push(item: T) { this.items.push(item); } pop(): T | undefined { return this.items.pop(); } print() { console.log(this.items.join(' -> ') + ' -> null'); } } const stack = new Stack<number>(); stack.push(1); stack.push(2); stack.push(3); stack.pop(); stack.print();
Remember that pop removes the last pushed item.
The stack pushes 1, 2, 3. Then pop removes 3. Remaining items are 1 and 2 in that order. Printing shows '1 -> 2 -> null'.
What is the printed output after running this TypeScript code that uses a queue?
class Queue<T> { private items: T[] = []; enqueue(item: T) { this.items.push(item); } dequeue(): T | undefined { return this.items.shift(); } print() { console.log(this.items.join(' -> ') + ' -> null'); } } const queue = new Queue<number>(); queue.enqueue(10); queue.enqueue(20); queue.enqueue(30); queue.dequeue(); queue.print();
Remember that dequeue removes the first item added.
The queue enqueues 10, 20, 30. Dequeue removes 10. Remaining items are 20 and 30. Printing shows '20 -> 30 -> null'.
Which option shows a problem when using a stack to implement an undo feature in a text editor?
class UndoStack { private stack: string[] = []; addAction(action: string) { this.stack.push(action); } undo(): string | undefined { return this.stack.pop(); } print() { console.log(this.stack.join(' -> ') + ' -> null'); } } const undoStack = new UndoStack(); undoStack.addAction('type A'); undoStack.addAction('type B'); undoStack.undo(); undoStack.print();
Think about how undo should remove the most recent action.
A stack correctly removes the last action added, which matches undo behavior. Other options describe incorrect behaviors not matching stack operations.
You want to implement browser history navigation with back and forward buttons. Which data structure or combination is best suited?
Consider how back and forward buttons move through history in opposite directions.
Two stacks allow moving back by popping from the back stack and pushing to the forward stack, and vice versa for forward navigation. A single stack or queue cannot handle forward navigation properly.
