Profile

Unblock all features

Sign in to track progress and visualise your code.

ntree.ai
Helper data structures and core patterns

Stack

A stack is a collection that gives back the most recent element first: last in, first out (LIFO). You should use a stack whenever the latest unfinished thing has to be handled first.

1
2
3
push adds to the top, pop takes the top

Time and space complexity

operationtime
add an element to the topO(1)O(1) amortised
remove the top elementO(1)O(1)
read the top elementO(1)O(1)

Implementation

Implementing a stack with an array is trivial, so we will not do it.

Also, when a problem needs a stack, we just use a dynamic array, which supports the same operations with the same time complexity. The more important part is to learn how to recognise when stack operations can be used, which comes with practice.

Was this lesson helpful?