Back to Practice Dashboard
Python BasicsEasy
Generate balanced parentheses
Learn how to solve the 'Generate balanced parentheses' problem. This detailed resource details brute force and optimized approaches.
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?
Use simple arithmetic operators (like modulo `%`, division `//`), conditional checks, or loops to inspect number properties.
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.