awelgorithms

Identify the top

Updated

The top is the only exposed value. In [4, 1, 9] the top is 9, not 4. Bottom is index 0 in this writing; top is the last index.

What to focus on

You name the top in O(1). You do not scan. After a push the new value is the top. After a pop the previous second-from-top becomes the top.

Worked examples

three items

a = [4, 1, 9]
  1. last slot is 9

Result: top is 9

one item

a = [7]
  1. the only item is the top

Result: top is 7

after push

a = [4, 1], push 9
  1. 9 is the new last slot

Result: top is 9

Try it

Write top(a). a is the stack, written [bottom, ..., top]. Return the top value. Do not pop. On [4, 1, 9] return 9. On [7] return 7. After push 9 onto [4, 1], top is 9.

The stack is non-empty. Values are integers.