Stacks
Learn the fundemantals of stacks, a core data structure based on the `LIFO` Last In First Out principle.

Stacks
A stack is an ordered collection of elements where elements are only added and removed from the same end.
In the physical world, and example of a stack would be a stack of plates in a kitchen - you add plates or remove plates from the top of the pile.
In the software world, a good example of a stack is the history of your current browsers tab.
Let's say you're on site A
, and you click on a link to go to site B
, then from B
you click on another like to go to site C
. Every time you click a link, you are adding to the stack - your history is now [A, B, C]
Another term used to describe stacks is LIFO, which stands for last in, first out. The last(most recent) element placed inside is the first element to come out.
Stack operations
// Declaration on Java
Stack<Integer> stack = new stack<>();
// Pushing elements.
stack.push(1);
stack.push(2);
// Popping elements.
stack.pop(); // 2
// Check if empty
stack.empty() // false
// Check element at top
stack.peek(); // 1
// Get size
stack.size(); // 1
Top Stack-Related Problems
String
String questions involving stakcs are popular.
20. Valid Parentheses
20. Valid ParenthesesGiven a string S
containing just the characters '(', ')', '{', '}', '[' and ']'
, determine if the input string is valid. The string is valid if all open brackets are closed by the same type of closing bracket in the correct order, and each closing bracket closes exactly one open bracket.