Back to all posts

Stack

3 min read
data-structuresstackcs-fundamentalsinterview-prep

LIFO (Last In, First Out) data structure. The last element pushed is the first popped. Think: browser back button, undo operations, call stack.

Core Structure

text
Stack:
  data[]
  top = -1

push(val):   data[++top] = val
pop():       return data[top--]
peek():      return data[top]
isEmpty():   return top == -1

Core Operations

OperationDescriptionTimeSpace
push(val)Add to topO(1)O(1)
pop()Remove from topO(1)O(1)
peek()View top without removingO(1)O(1)
isEmpty()Check if emptyO(1)O(1)

Implementations

Backing StructureNotes
ArrayFixed or dynamic size, cache-friendly
Linked ListDynamic size, pointer overhead
text
// Array-backed
push(val):  arr[++top] = val
pop():      return arr[top--]

// LinkedList-backed
push(val):  node = Node(val); node.next = head; head = node
pop():      val = head.value; head = head.next; return val

Valid Parentheses

Push open brackets, pop and match on close brackets.

text
isValid(s):
  stack = []
  for ch in s:
    if ch in '([{': stack.push(ch)
    else:
      if stack.isEmpty(): return false
      if !matches(stack.pop(), ch): return false
  return stack.isEmpty()
TimeSpace
ComplexityO(n)O(n)

Evaluate Expression (Postfix)

text
evalPostfix(tokens):
  stack = []
  for token in tokens:
    if isNumber(token):
      stack.push(token)
    else:
      b = stack.pop()
      a = stack.pop()
      stack.push(apply(a, token, b))
  return stack.pop()
TimeSpace
ComplexityO(n)O(n)

Monotonic Stack

Stack that maintains elements in increasing or decreasing order. Used for "next greater/smaller element" problems.

text
nextGreater(arr):
  stack = []
  result[0..n] = -1
  for i from 0 to n:
    while stack not empty and arr[stack.top()] < arr[i]:
      idx = stack.pop()
      result[idx] = arr[i]
    stack.push(i)
  return result
TimeSpace
ComplexityO(n)O(n)

Each element is pushed and popped at most once — total O(n) even with the inner while loop.


Common Interview Patterns

PatternProblem Examples
Matching/balancingValid parentheses, HTML tag validation
Monotonic stackNext greater element, daily temperatures
Expression evaluationPostfix, infix-to-postfix conversion
DFS simulationTree/graph traversal without recursion
Undo/redo mechanicsText editor, browser history

Quick Reference

Stack
OrderLIFO
Insertpush → top
Removepop ← top
Peektop element
OverflowPush on full stack
UnderflowPop on empty stack