What is a balanced parentheses problem and how to solve it?
Answer
The balanced parentheses problem checks if a string of brackets is valid — every opening bracket has a corresponding closing bracket in the correct order. Uses a stack. Algorithm: iterate the string; push opening brackets onto the stack; for closing brackets, check if stack is non-empty and top is the matching opening bracket; if not, invalid; at end, if stack is empty, valid. Example: valid: "([])", "()[]{}"; invalid: "(]", "([)]", "{". Time: O(n). Space: O(n). Extension — Minimum insertions to balance: track open and close counts; for each '(': open++; for each ')': if open > 0 open-- else close++; answer = open + close. Generate all valid parentheses (Leetcode 22): backtracking — track open and close counts; add '(' if open < n; add ')' if close < open; O(Catalan(n)). Longest valid parentheses (Leetcode 32): DP or stack — O(n). Score of parentheses: assign scores recursively. Related problems: (1) Remove minimum invalid parentheses; (2) Check if paths in a matrix form valid parentheses; (3) Minimum add to make valid. The stack-based bracket matching pattern extends to: matching HTML tags, checking XML, and parsing arithmetic expressions.