FrontendInterviews.dev

Loading problem…

261. Valid Parentheses IV - Generate Valid Parentheses

Medium•
Acceptance: 85.00%
•
🔓3/3 Pro unlocks today

This problem builds on valid-parentheses-iii. Complete that first, then load your solution to continue.

You're building a code generator that needs to generate all valid combinations of parentheses. This is useful for generating test cases, creating balanced expressions, or building parser test data.

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Requirements

1. Basic Functionality

  • Generate all valid parentheses combinations
  • Each combination must have n pairs
  • Parentheses must be well-formed (balanced)
  • Return array of all valid strings

Example Usage

generateParenthesis(3);
// ["((()))","(()())","(())()","()(())","()()()"]

generateParenthesis(1);
// ["()"]

Real-World Context

This problem models real code generation scenarios:

  • Code generation: Generate valid code structures
  • Parser testing: Create test cases for parsers
  • Expression generation: Generate balanced expressions
  • Combinatorics: Generate all valid combinations

Constraints

  • 1 <= n <= 8
  • Return all valid combinations
  • Each combination has exactly n pairs
  • Parentheses must be balanced