awelgorithms

Avoid scanning under the top

Updated

If you walk past the top to read a buried value, you are using the backing array, not the ADT. That breaks the LIFO contract and often turns O(1) into O(n). Prefer pop, a second stack, or a different structure.

What to focus on

Legal O(1) reads: top, size, isEmpty. Illegal: third from top without popping, min by scanning (unless you stored min on pairs).

Worked examples

legal peek

a = [4, 1, 9]
  1. read 9 only

Result: O(1) ADT

illegal bury

a = [4, 1, 9], read index 0 as 'bottom' through ADT
  1. not a stack op

Result: cheating / O(1) array not stack

min scan

a = [4, 1, 9], min by walking all
  1. O(n)
  2. or O(1) with min pairs

Result: scan is not peek

Try it

Write legalReads(a). a is the stack written bottom to top. List the legal O(1) queries: peek, size, isEmpty. A buried read is outside the ADT. Min is O(n) scan or O(1) stored extra. a = [4, 1, 9] → O(1) ADT. a = [4, 1, 9], read index 0 as 'bottom' through ADT → cheating / O(1) array not stack. a = [4, 1, 9], min by walking all → scan is not peek.

The stack is non-empty. Values are integers. Only peek, size, and isEmpty are ADT reads.