Problem 20

Abstract / Summary

Check if all opening parentheses are closed by the same type in the correct order.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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();
    }
};

33 lines | 988 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 45% (10+ million submissions).

Typical patterns to solve this problem:
  • Stack
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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(); yields true, correctly treating an empty sequence as valid.
  • A string that begins with a closing bracket triggers the stack.empty() check, causing an immediate false return, handling cases such as "]" or ")}".
  • A string with a mismatched pair, for example "([)]", passes the stack.empty() test for the first closing bracket but fails the stack.back() != '[' comparison, leading to a false result.
  • Excess opening brackets, such as "(((", leave elements in the stack after the loop, and the final emptiness test returns false.
  • 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_back and pop_back methods of vector operate in amortized constant time, ensuring that each character is processed with minimal per-iteration cost.
  • The switch statement provides a compile-time dispatch mechanism that is more efficient than a series of if-else comparisons, 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.
written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 29 | median = 8 | μ = 7.86 | σ = 0.90

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
67 links | 47 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'LeetCode 20. Valid Parentheses Solution Explained - Java'
Nick White 8 mins
LeetCode 20. Valid Parentheses Solution Explained - Java
YouTube video 'Valid Parentheses (LeetCode 20) | Full solution with visuals and animations | Stack Data Structure'
Nikhil Lohia 16 mins
Valid Parentheses (LeetCode 20) | Full solution with visuals and animations | Stack Data Structure
YouTube video 'Valid Parentheses - Leetcode 20 - Stacks (Python)'
Greg Hogg 9 mins
Valid Parentheses - Leetcode 20 - Stacks (Python)
YouTube video 'Valid Parentheses | LeetCode 20 | Easy'
Code And Coffee 7 mins
Valid Parentheses | LeetCode 20 | Easy
YouTube video 'Valid Parentheses | Leetcode - 20 | Google, Meta | Explanation ➕ Live Coding Trash'
codestorywithMIK 10 mins
Valid Parentheses | Leetcode - 20 | Google, Meta | Explanation ➕ Live Coding Trash
YouTube video '20. Valid Parentheses || Java || Leetcode || Hindi'
Coding Sphere 12 mins
20. Valid Parentheses || Java || Leetcode || Hindi
YouTube video 'Valid Parentheses using O(1) Space | Live Coding with Explanation | Leetcode - 20'
Algorithms Made Easy 14 mins
Valid Parentheses using O(1) Space | Live Coding with Explanation | Leetcode - 20
YouTube video 'Valid Parentheses - LeetCode 20 - Coding Interview Questions'
One Code Man 3 mins
Valid Parentheses - LeetCode 20 - Coding Interview Questions
YouTube video 'Valid Parentheses - LeetCode 20 - JavaScript'
AlgoJS 7 mins
Valid Parentheses - LeetCode 20 - JavaScript
YouTube video 'Valid Parentheses | Leetcode 20 | Stack | Day-13'
Ayushi Sharma 10 mins
Valid Parentheses | Leetcode 20 | Stack | Day-13
YouTube video 'Leetcode 20. Valid Parentheses'
Pratiksha Bakrola 8 mins
Leetcode 20. Valid Parentheses
YouTube video 'Leetcode 20: Valid Parentheses Explained in Telugu | Brute Force & Stack Approach | srkcodes'
Srk Codes 15 mins
Leetcode 20: Valid Parentheses Explained in Telugu | Brute Force & Stack Approach | srkcodes
YouTube video '[Java] Leetcode 20. Valid Parentheses [Stack & Queue #3]'
Eric Programming 10 mins
[Java] Leetcode 20. Valid Parentheses [Stack & Queue #3]
YouTube video 'Valid Parentheses | LeetCode 20 | Theory + Python code'
Sai Anish Malla 12 mins
Valid Parentheses | LeetCode 20 | Theory + Python code
YouTube video 'Valid Parentheses Python Solution - LeetCode #20'
Professor Oakes 5 mins
Valid Parentheses Python Solution - LeetCode #20
YouTube video 'LeetCode 20: Valid Parentheses - Interview Prep Ep 7'
Fisher Coder 14 mins
LeetCode 20: Valid Parentheses - Interview Prep Ep 7
YouTube video 'Valid Parentheses | valid parentheses | leetcode 20 | stack'
Naresh Gupta 7 mins
Valid Parentheses | valid parentheses | leetcode 20 | stack
YouTube video '20. Valid Parentheses | JavaScript | Stack | LeetCode Daily Challenge'
LeetCodeWithMonu 13 mins
20. Valid Parentheses | JavaScript | Stack | LeetCode Daily Challenge
YouTube video 'LeetCode 20: Valid Parentheses | C# Solution | Stack Implementation |'
Code Scribbler 8 mins
LeetCode 20: Valid Parentheses | C# Solution | Stack Implementation |
YouTube video 'Valid Parentheses - LeetCode #20 - C++'
Sean Chuah 3 mins
Valid Parentheses - LeetCode #20 - C++
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

6 similar problems

Solved On The Same Day

18 easy 43 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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