Opening your learning path
Progress is saved as you study.
Opening your learning path
Progress is saved as you study.
The Valid Parentheses Matching pattern applies when you need the Valid Parentheses Matching technique within the Stack Patterns pattern. Its time complexity is O(n) and space complexity O(n). It is used in 6 problems on Thita, including Longest Valid Parentheses, Minimum Add to Make Parentheses Valid and Minimum Number of Swaps to Make the String Balanced. Common variations are Largest Rectangle in Histogram and Monotonic Stack.
Master parentheses validation and balancing using stack. Handle multiple bracket types and minimum additions.
Valid Parentheses Matching is one of the 6 subpatterns of the Stack Patterns pattern, which covers parentheses matching, monotonic stack, histogram, and expression evaluation. The whole pattern is about 2.5 hours of study. This subpattern is a core technique: expect it to come up directly in interviews.
Master stack-based algorithms including valid parentheses, monotonic stack for next greater element, expression evaluation, and histogram problems. Problems in this subpattern are usually searched for as valid parentheses, bracket matching, balanced parentheses, stack parentheses, leetcode 20.
Read the theory for Valid Parentheses Matching, then work the problems attached to it in the browser editor. Your solution runs against the problem's test cases, and the AI coach offers a hint about the technique you are missing rather than a finished solution. Progress is tracked per subpattern, so the Stack Patterns tracker shows this one as covered once you have solved its problems.
Valid Parentheses Matching is one lesson in a 16-pattern DSA course. If you are preparing end to end, work the interview-critical patterns first and use the pattern sheet as the checklist; if you are here for one technique, the Stack Patterns guide is the shortest path back to the rest of it.
6 problems, easiest first.
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!