awelgorithms

Count items on a stack

Updated

Size is how many values are currently on the stack. You maintain it on each push (+1) and pop (−1), or you read the backing length. Empty is 0.

What to focus on

Size is not the top. Size 3 with top 9 is [?, ?, 9]. You can know size without knowing buried values, if you store a counter.

Worked examples

three

a = [4, 1, 9]
  1. three pushes, no pops

Result: size 3

after pop

a = [4, 1, 9], pop
  1. size was 3
  2. now 2

Result: size 2

empty

a = []
  1. no items

Result: size 0

Try it

Write size(a). a is the stack, written [bottom, ..., top]. Return how many values are on the stack. Size tracks push and pop, not the top value. On [4, 1, 9] return 3. After one pop return 2. On [] return 0.

Values are integers. The stack may be empty.