DSABeginner6 min readPart 6 of 16

Stack and Queue

Stacks and queues are simple linear data structures that control the order you take elements out. They show up in tree traversals, BFS and DFS, expression evaluation and scheduling problems.

Can you explain stack and queue out loud?

I'm Alex. Read this, then I'll interview you on real problems and push on the parts you skip.

Stack vs queue in one pictureCore idea

stack (LIFO)123← topPush and pop at the top: 3 went in last, so it comesout first.queue (FIFO)123frontbackJoin at the back, leave from the front: 1 went infirst, so it comes out first.
DiagramSame three items, opposite exit order.

Stack: last in, first outHow it works

The last element pushed is the first popped (LIFO). Think of a stack of plates: you add and remove from the top.

Stack operationsTypeScript
const stack: number[] = [];
stack.push(1);    // [1]
stack.push(2);    // [1, 2]
stack.push(3);    // [1, 2, 3]
stack.pop();      // returns 3, stack is [1, 2]
stack[stack.length - 1]; // peek: returns 2

Balanced parentheses

Push opening brackets, pop on each closing one. Balanced if the stack is empty at the end.

Next greater element

A monotonic stack, explained below.

Evaluate expressions

Push operands, pop them when you reach an operator.

DFS traversal

Recursive DFS uses the call stack, which is a stack.

Queue: first in, first outHow it works

The first element added is the first removed (FIFO). Think of a line at a shop: the first person in line is served first.

Queue operations (array + shift, or a deque)TypeScript
const queue: number[] = [];
queue.push(1);    // enqueue: [1]
queue.push(2);    // [1, 2]
queue.shift();    // dequeue: returns 1, queue is [2]

BFS traversal

BFS uses a queue to explore a graph level by level.

Task scheduling

Round-robin scheduling handles tasks in FIFO order.

Sliding window maximum

A deque keeps the candidates for the current maximum.

Monotonic stackPattern

A stack whose values are always increasing (or always decreasing) from bottom to top. Each new element pops every element it beats, and those popped elements have just found their “next greater element”. Every index is pushed and popped once, so the whole scan is O(n).

Next greater element for [2, 1, 5]

before 5 arrives21← topThe stack holds values still waiting for a bigger one.after 5 arrives5← top5 pops 1 and 2: both of their next greater elementsare 5.
Next greater element: O(n)TypeScript
function nextGreaterElement(nums: number[]): number[] {
  const result = new Array(nums.length).fill(-1);
  const stack: number[] = []; // stores indices
  for (let i = 0; i < nums.length; i++) {
    while (stack.length && nums[stack[stack.length - 1]] < nums[i]) {
      result[stack.pop()!] = nums[i];
    }
    stack.push(i);
  }
  return result;
}
TimeO(n)SpaceO(n)

Deque (double-ended queue)Core idea

A deque adds and removes at both ends in O(1). It can act as a stack or a queue, and it is the tool behind the sliding window maximum.

StructureAddRemoveTypical use
StackTopTopDFS, brackets, monotonic stack
QueueBackFrontBFS, scheduling
DequeBoth endsBoth endsSliding window maximum

Common mistakesPitfalls

Using shift() as a queue in JavaScriptshift() is O(n). For large inputs, use a real queue or a head index.
No visited setWhen walking a graph with a stack or queue, always track visited nodes.
Mixing up stack and queueDFS uses a stack, BFS uses a queue. Swapping them changes the traversal order.
Forgetting leftovers in a monotonic stackElements still on the stack at the end have no next greater element.
Skipping edge casesEmpty input, a single element, all elements identical.

In the interviewIn the interview

Frequently asked questionsFAQ

What is the difference between a stack and a queue?

A stack is last-in-first-out, like a stack of plates, with push and pop from the same end. A queue is first-in-first-out, like a ticket line, with insert at the back and removal from the front. Both support their core operations in O(1).

What is a monotonic stack and when do you use it?

A monotonic stack keeps its elements in sorted order by popping smaller or larger entries before pushing, so it maintains useful boundaries as you scan left to right. It is the standard O(n) solution for next-greater-element, largest-rectangle-in-histogram, and daily-temperatures, where a plain stack would rescan the same regions repeatedly.

Which queue variant is best for breadth-first search?

A plain first-in-first-out queue gives the standard BFS level order. A deque, or double-ended queue, is used when some entries must be pushed to the front, as in 0-1 BFS for shortest paths on weighted graphs. Pointer-based queues are preferred over shifting array queues at scale.

Now explain stack and queue to me out loud

I'll give you interview problems and ask follow-ups, like a real interviewer.

Practice with Alex

Keep readingKeep reading

Ready to practice?

Reading is step one. Saying it out loud is step two.

Start a mock interview with Alex, get pushed on the parts you skip, and see your hiring signal right after.