Skip to content

stack / heap [terminology]

Terminology

Usage

  • Keep these names rather than abbreviating them.
  • They identify both the data structure and its algorithmic behavior.
  • Use stack for LIFO processing and heap for priority-based processing.
stack = []
for token in tokens:
    if token not in {"+", "-", "*", "/"}:
        stack.append(int(token))
        continue
    right = stack.pop()
    left = stack.pop()
    # ...

See 150. Evaluate Reverse Polish Notation.

heap = []
for x in nums:
    if len(heap) < k:
        heapq.heappush(heap, x)
    elif x > heap[0]:
        heapq.heapreplace(heap, x)

See 215. Kth Largest Element in an Array.