Skip to content

visual walkthrough

Valid Parentheses

EasyMatching / ParsingReported at: AmazonMetaMicrosoft+16

The canonical stack question; often the first problem in a phone screen.

Solve on LeetCode

The idea

Brackets nest: the last one opened must be the first one closed. That is exactly what a stack does. Push each opener; when a closer arrives it must match the opener on top.

At the end the stack must be empty, otherwise some opener was never closed.

Complexity

approachtimespace
Delete matching pairsO(n²)O(n)
StackO(n)O(n)

More walkthroughs