What is a balanced parentheses problem and how to solve it?

Why Interviewers Ask This

This tests whether you can apply Data Structures & Algorithms knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.

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.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Data Structures & Algorithms codebase.