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
| operation | time |
|---|---|
| add an element to the top | amortised |
| remove the top element | |
| read the top element |
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?