Algorithms from zero
Lists, stacks, queues: multiple-choice review
Six questions that cut across the whole unit. Each one is a decision an interviewer pushes on — not a definition to recite, but a cost model to defend and an implementation choice to justify.
Confirm you can connect the memory layout of a linked list to its cost model, reason about pointer manipulation without losing nodes, pick the right LIFO/FIFO discipline for a problem, and explain why a monotonic stack is linear despite its inner loop.
A workload pushes at the head 10,000 times and then reads by index 100 times at random positions. You must pick array vs singly linked list. Which is faster overall, and why?
You are writing in-place reversal of a singly linked list. A colleague writes current.next = prev; current = current.next; inside the loop. What breaks?
You repeatedly insert and delete at the head of a singly linked list and keep hitting null-pointer special cases for the empty-list and head positions. What is the cleanest structural fix?
You are validating nested brackets in a config parser, and separately you are doing a level-order (breadth-first) walk of a tree. Which structures fit, and why?
You implement a FIFO queue on a JavaScript array using push to enqueue and shift to dequeue. Under a sustained stream of N enqueue+dequeue pairs, what is the total cost and the fix?
A monotonic-stack solution to next-greater-element has a while loop inside a for loop, yet it is O(n), not O(n^2). What is the precise argument?
The through-line of the unit is one cost model and three disciplines. Memory layout sets the cost: contiguity buys O(1) indexing, scattering buys O(1) head insertion — you choose based on the dominant operation. Pointer manipulation is about saving links before you overwrite them and using a sentinel to erase head special cases. The stack (LIFO) and queue (FIFO) are disciplines, not data structures: pick by whether you need most-recent-first or arrival-order, and never dequeue with shift. The monotonic stack is the payoff — a stack plus an ordering invariant turns an O(n^2) scan into O(n) by the push-once/pop-once amortized argument.