Length 1:13Loading the video
Loading the video
Is every bracket closed by its partner, in the right order? Two ways to check: deleting matching pairs again and again, and a stack that matches every closer in one pass.
Narrated by an AI voice.
LeetCode problem twenty gives you a string of brackets.
They come in round, square and curly kinds.
Is each one closed by its partner, in the right order?
This string nests a square pair and a curly pair inside a round pair.
It is valid.
This one closes round before square, so it is invalid.
The first way: a valid string always has a matching pair side by side.
Delete those pairs again and again.
If nothing is left, it was valid.
In JavaScript, a loop removes each kind of pair with replace.
It stops when the length no longer changes.
Then we return whether the string is empty.
This is easy to read, but slow.
Each pass scans the string and may remove one pair.
That is about n squared steps, and the copies take extra memory that grows with n.
The second way uses a stack, like a pile of plates.
An opening bracket goes on top.
A closing bracket must match the top, and then we pop it off.
Take the bad string.
Round goes on the stack.
Square goes on top.
Then a round closer comes, but the top is square.
That is a mismatch, so we return false.
In code, a map pairs each closer with its opener.
We loop over the characters.
Openers are pushed.
A closer pops the top and compares it with the map.
At the end, the stack must be empty.
Each character is pushed and popped at most once.
So the time grows in a straight line with n, and the stack holds up to n brackets.
Removing pairs works, but it is slow.
A stack checks every bracket in one pass.
Type any algorithm, interview problem or system, and get your own narrated video.
3 free videos with your own AI key. An AI key is a code from an AI company, such as Anthropic or OpenAI. Your own AI account pays for the writing. See pricing
Make a video
Length 1:13
Length 2:20
Length 1:56