awelgorithms

Read the stack size

Updated

Size is a count you can read in O(1) if you store it, or O(n) if you walk a list-backed stack without a counter. Prefer a stored size.

What to focus on

size() does not change the stack. size 0 iff isEmpty. After push, size+1; after pop, size−1. Do not confuse size with the top value.

Worked examples

three

a = [4, 1, 9]
  1. count 3

Result: 3

after push

a = [4, 1, 9], push 8
  1. 4

Result: 4

empty

a = []
  1. 0

Result: 0

Try it

Write size(a). a is the stack, written [bottom, ..., top]. Return the count. Do not change the stack. Size is not the top value. Print 3 for [4, 1, 9], 4 after push 8, 0 for [].

Values are integers. The stack may be empty.