StackMedium

Balanced Parentheses

Balanced Parentheses Algorithm

Matching bracket problems are classical compiler syntax checking applications.

Algorithm Logic

  1. Scan Expression: Iterate through each character in the string sequence from left to right.
  2. Push Opening Brackets: If the character is an opening bracket ((, {, [), push it onto the stack.
  3. Handle Closing Brackets: If the character is a closing bracket (), }, ]):
    • Check if stack is empty. If empty, the brackets are unbalanced (closing bracket without opening).
    • Pop the top bracket off the stack and check if it is of matching type (e.g. ( matches )). If not, brackets are unbalanced.
  4. Final Check: After scanning the entire string, the stack should be empty. If it is not, some opening brackets were left unmatched, making it unbalanced.