Data Structures19 sections · 729 units
Open in Course

Valid Parentheses - Algorithm

Push and match

The algorithm is simple:

1.1. For each character in the string:

  • If it's an open bracket, push it onto the stack.
  • If it's a close bracket, check if the stack is non-empty and the top matches. If so, pop. Otherwise, return false.

2.2. After processing all characters, return true if the stack is empty. An empty stack at the end means every open found its matching close. Time: O(n)O(n). Space: O(n)O(n).