Opening your learning path
Progress is saved as you study.
Opening your learning path
Progress is saved as you study.
The Stack Patterns pattern applies when you need parentheses matching, monotonic stack, histogram, and expression evaluation. Its time complexity is O(n) and space complexity O(n). It is used in 29 problems on Thita, including Asteroid Collision, Baseball Game and Basic Calculator. Common variations are Largest Rectangle in Histogram and Valid Parentheses Matching.
Master stack-based algorithms including valid parentheses, monotonic stack for next greater element, expression evaluation, and histogram problems.
Stack Patterns is pattern 6 of 16 in the Thita.ai DSA course. It covers parentheses matching, monotonic stack, histogram, and expression evaluation, split into 6 subpatterns and about 2.5 hours of study. It is one of the interview-critical patterns, so it is worth covering before your first onsite.
Each subpattern below has its own theory page and problem set. They are listed in the order the course teaches them.
Read the theory for a subpattern, then solve its problems in the browser editor. Your solution runs against the problem's test cases, and the AI coach gives a hint on the technique you are missing rather than the finished answer. Progress is tracked per subpattern, so the tracker shows which of the 6 Stack Patterns subpatterns you have covered. Topics covered here include stack patterns, stack algorithms, valid parentheses, monotonic stack, next greater element, expression evaluation, largest rectangle histogram, stack interview questions.
Imagine you’re stacking plates in your kitchen: every time you put a plate on the stack, you expect to remove it in the reverse order you placed it. This is the essence of the stack data structure—a “last in, first out” (LIFO) system. Now, think of parentheses in a math equation or code: every opening bracket (, {, or [ must be matched and closed in the correct order. If you open a bracket, you need to close it before closing any previous ones—just like you can’t remove a plate from the middle of your stack!
Valid Parentheses Matching is all about ensuring every opening bracket has a corresponding closing bracket, and that they’re properly nested. This pattern is crucial in real-world scenarios like:
Whenever you need to verify or manipulate nested structures—like undo/redo operations, parsing expressions, or even checking if a string is a palindrome—stack patterns, especially parentheses matching, come into play. It’s like making sure every opened door is eventually closed, and in the right order!
Let’s break down the magic behind parentheses matching:
Think of a stack as a pile of sticky notes. Every time you see an opening bracket, you write it down and stick it on top. When you see a closing bracket, you check the top sticky note: does it match? If yes, remove it. If not, something’s wrong!
( with )).Some problems ask you to:
These variations might use stacks, two pointers, or even dynamic programming, but the core idea remains: track the “openings” and ensure they’re properly matched.
Let’s build a mental checklist for tackling parentheses matching problems:
Ask yourself:
For s = "([{}])":
( → stack: ([ → stack: ([{ → stack: ([{} → matches { on top, pop.] → matches [ on top, pop.) → matches ( on top, pop.Let’s implement the Valid Parentheses (Easy) problem:
1#include <iostream>
2#include <stack>
3#include <unordered_map>
4#include <string>
5
6// Function to check if the input string has valid parentheses
7bool isValidParentheses(const std::string& s) {
8 // Map to match closing to opening brackets
9 std::unordered_map<char, char> bracketPairs = {
10 {')', '('},
11 {']', '['},
12 {'}', '{'}
13 };
14
15 std::stack<char> stk; // Stack to keep track of opening brackets
16
17 for (char ch : s) {
18 // If it's an opening bracket, push to stack
19 if (ch == '(' || ch == '[' || ch == '{') {
20 stk.push(ch);
21 }
22 // If it's a closing bracket
23 else if (ch == ')' || ch == ']' || ch == '}') {
24 // If stack is empty or top doesn't match, invalid
25 if (stk.empty() || stk.top() != bracketPairs[ch]) {
26 return false;
27 }
28 stk.pop(); // Pop the matched opening bracket
29 }
30 // Ignore any other characters (if problem allows)
31 }
32
33 // If stack is empty, all brackets matched
34 return stk.empty();
35}
36
37int main() {
38 std::string test = "{[()]}";
39 std::cout << (isValidParentheses(test) ? "Valid" : "Invalid") << std::endl;
40 return 0;
41}Explanation:
Let’s walk through Minimum Remove to Make Valid Parentheses (Medium):
Step-by-step intuition:
'('.')', if the stack is not empty, pop (they match). If the stack is empty, mark this ')' for removal.'('—mark them for removal.Why stack?
'(' that haven’t been matched yet, just like keeping track of open doors you need to close.Example:
"a)b(c)d"')' has no matching '(', so mark for removal.'('."ab(c)d"Key pattern connection:
Remember: Whenever you see a problem about matching pairs in a specific order, think “stack!” It’s your go-to tool for keeping track of what’s open and making sure everything gets closed in the right order. Happy coding!