C++ 0020.cpp
class Solution {
public:
bool isValid(string s) {
vector<char> stack;
for (auto c : s)
switch (c)
{
case '(':
case '{':
case '[':
stack.push_back(c);
break;
case ']':
if (stack.empty()) return false;
if (stack.back() != '[') return false;
stack.pop_back();
break;
case '}':
if (stack.empty()) return false;
if (stack.back() != '{') return false;
stack.pop_back();
break;
case ')':
if (stack.empty()) return false;
if (stack.back() != '(') return false;
stack.pop_back();
break;
}
return stack.empty();
}
};
Difficulty
and has an acceptance rate of about 45% (10+ million submissions).
Typical patterns to solve this problem:
- Stack
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation validates a string containing only the characters (, ), {, }, [ and ]. It determines whether the brackets are correctly nested and closed in the proper order. The algorithm employs a dynamic array (vector<char>) as a stack to keep track of opening brackets encountered while scanning the input from left to right. Each character is processed by a switch statement that either pushes an opening bracket onto the stack or checks the top of the stack for a matching opening bracket when a closing bracket is seen. At the end of the scan the string is considered valid only if the stack is empty.
Key Steps
The core of the algorithm consists of three distinct actions: initialization of the stack, per-character processing, and final validation.
Stack initialization
vector<char> stack;
A vector<char> is created to serve as a stack. The choice of vector provides contiguous storage and amortized constant-time push and pop operations.
Iterating over the input string
for (auto c : s)
switch (c)
{
case '(':
case '{':
case '[':
stack.push_back(c);
break;
// handling of closing brackets follows
}
The range-based for loop extracts each character c from the input string s. The switch statement groups the three opening brackets together, allowing a single push_back operation for any of them.
Matching closing brackets
case ']':
if (stack.empty()) return false;
if (stack.back() != '[') return false;
stack.pop_back();
break;
case '}':
if (stack.empty()) return false;
if (stack.back() != '{') return false;
stack.pop_back();
break;
case ')':
if (stack.empty()) return false;
if (stack.back() != '(') return false;
stack.pop_back();
break;
For each closing bracket the code first checks whether the stack is empty, which would indicate an unmatched closing bracket. It then verifies that the top of the stack contains the corresponding opening bracket. If both checks succeed, the matching opening bracket is removed from the stack.
Final validation
return stack.empty();
After processing all characters, the string is valid only if no unmatched opening brackets remain, which is indicated by an empty stack.
Edge Cases Handled
The implementation explicitly guards against several edge conditions:
- An empty input string results in an empty stack from the start, and the final
return stack.empty();yieldstrue, correctly treating an empty sequence as valid. - A string that begins with a closing bracket triggers the
stack.empty()check, causing an immediatefalsereturn, handling cases such as"]"or")}". - A string with a mismatched pair, for example
"([)]", passes thestack.empty()test for the first closing bracket but fails thestack.back() != '['comparison, leading to afalseresult. - Excess opening brackets, such as
"(((", leave elements in the stack after the loop, and the final emptiness test returnsfalse. - Interleaved correct nesting, like
"{[()]}", passes all checks because each closing bracket finds its matching opening counterpart at the top of the stack.
Performance Optimizations
The code leverages several low-overhead techniques:
- Using a
vector<char>as the stack avoids the overhead of a linked-list based container; memory is contiguous, which improves cache locality during push and pop operations. - The
push_backandpop_backmethods ofvectoroperate in amortized constant time, ensuring that each character is processed with minimal per-iteration cost. - The
switchstatement provides a compile-time dispatch mechanism that is more efficient than a series ofif-elsecomparisons, especially given the small, fixed set of possible characters. - Early returns on failure conditions (
stack.empty()or mismatched top element) prevent unnecessary processing of the remaining characters once an invalid state is detected, reducing the total work for malformed inputs.
ELI5 - Simplified Explanation
Imagine you have a toy box where you can only put things in and take them out from the very top. This code is like a little helper making sure that every time you open a pair of brackets, like the curly ones or the round ones, you close them in the right order.
The helper looks at each bracket one by one as it goes through a line. When it sees an opening bracket, it places it inside the toy box to remember it for later. When it sees a closing bracket, it reaches into the box to grab the last one put inside. It checks if the one it grabbed matches the closing bracket it just found. If they are a perfect match, it takes that opening bracket out and keeps going. If the box is empty when it needs to find a match, or if the brackets do not match correctly, the helper knows something is wrong with the pattern. After looking at every single bracket, the helper checks the box one last time to make sure every opening bracket was paired up and taken out, leaving the box completely empty.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||||
| WalkCCC | C++ | Python | Java | ||||||||||
| leetcode.ca | C++ | Python | Java | C# | Rust | JS | Go | TS | Ruby | PHP | |||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | AdelDaniel | Dart | |||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++ | ||||||||||||
| bujosa | Python | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| everthis | JS | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| gouthampradhan | Java | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| Krazune | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| luangong | C++ | TS | |||||||||||
| MacJim | C++ | ||||||||||||
| muhammadfarhankt | Go | ||||||||||||
| pruthvikp | Python | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| Shamik07 | Dart | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, PHP, Python, Ruby, Rust, TypeScript | ||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| AdelDaniel | Dart | ||||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++, C++ | ||||||||||||
| bujosa | Python | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| gouthampradhan | Java | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| Krazune | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| luangong | C++, TypeScript | ||||||||||||
| MacJim | C++ | ||||||||||||
| muhammadfarhankt | Go | ||||||||||||
| pruthvikp | Python | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| Shamik07 | Dart | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 22: Generate Parentheses
- problem 32: Longest Valid Parentheses
- problem 301: Remove Invalid Parentheses
- problem 1003: Check If Word Is Valid After Substitutions
- problem 2116: Check if a Parentheses String Can Be Valid
- problem 2337: Move Pieces to Obtain a String
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality