Algorithms for Interview 1: Stack
Introduction of Stack
Look at the above photo of plates, every pile of plates can represent a Stack.
Stack is an basic data structure and very useful to solve many problems. It is a array which has LIFO (last in, first out) feature.
This feature means:
- Last In: If we wanna add a new element to a stack, we must add it to the top of the stack rather than other locations. Just like a pile of plates, we can only add a new plate at top every time.
- First Out: If we wanna remove a existing element from a Stack, we can only remove the element at top which is the last in element. Just like a pile of plates, we can only remove the top plate every time.
Therefore, there are two principal functions of a Stack:
- push(): Add an element to the top of the stack
- pop(): Remove the top element
Interview Example 1:
Problem Description:
This problem is from LeetCode 20. Valid Parentheses.
Solution:
This is a very classic Stack problem.
We can use a Stack to store previous checked brackets. When we meet a ‘closed’ bracket, the top of the Stack must be a corresponding ‘open’ bracket. If not, we return False. If yes, we pop the top element of the Stack.





