Each of these costs O(1). You only ever touch one end, so nothing shifts or searches. push and pop just adjust the top position and one value. peek reads a single slot. Calling pop or peek on an empty stack is an underflow, so check isEmpty first.
That constant cost is the whole appeal. No matter how many items sit below, the top operations stay instant. This is why stacks handle deep call chains and long undo histories without slowing down.
Rewriting in plainer words…
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
What should pop do when the stack is empty?Compare throwing an error with returning a marker like null, and say what each one makes the caller check.
What would it cost to find a value somewhere inside the stack?Say O(n). Only the top is exposed, so you walk down item by item. If you need to search often, a stack is the wrong structure.
What you can say
A stack gives you four operations, and every one of them works on a single end, the top.
push puts an item on top, pop removes and returns the top item, peek reads it without removing it, and isEmpty tells you whether anything is left.
Each one is O(1), because you only adjust the top position and touch one value, so nothing shifts and nothing gets searched.
Calling pop or peek on an empty stack is an underflow, so I'd check isEmpty first.
That constant cost is why stacks handle deep call chains and long undo histories without slowing down, however many items sit below the top.
The catch is that you only get the top, so reaching anything deeper means popping down to it, and that costs time in proportion to how deep it sits.
Weak answers to avoid
Lists the operations but skips the costsThe question asks what they cost. Give O(1) for each and say why. Only the top moves, so nothing shifts or gets searched.
Says O(1) without saying whyAnyone can recite the number. The interviewer wants the reason, which is that you touch one end, so the work never depends on how many items sit below.
Forgets the empty-stack caseSkipping underflow hints at buggy code. Say that pop or peek on an empty stack is an error and that you check isEmpty before calling them.
Treats the stack like an indexable arrayA stack exposes only the top. Reading or finding an item deeper down means popping or walking to it, which is O(n), not O(1).
Interview lens
Likely follow-ups, what you can say, and the weak answers to avoid.