Python BasicsEasy

Generate balanced parentheses

Detailed guide and Python implementation for the 'Generate balanced parentheses' problem.

Problem Statement

Easy

Write a function generate_parentheses(n) that generates all combinations of n pairs of well-formed (balanced) parentheses. Return the result as a sorted list of strings. A string of parentheses is balanced if every opening '(' has a corresponding closing ')' and they are properly nested.

Constraints
  • 1 <= n <= 8

Examples

Example 1
Input
n = 3
Output
['((()))', '(()())', '(())()', '()(())', '()()()']
Explanation

All 5 valid ways to arrange 3 pairs of parentheses.

Example 2
Input
n = 1
Output
['()']
Explanation

Only one way to arrange 1 pair of parentheses.

Example 3
Input
n = 2
Output
['(())', '()()']
Explanation

Two valid arrangements: nested or sequential.

Need a Hint?
Consider using Recursion-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.