Tutorialspoint
Problem
Solution
Submissions

Generate Parentheses

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C program to generate all possible valid combinations of n pairs of parentheses. A valid parentheses combination is one where every opening parenthesis '(' has a corresponding closing parenthesis ')', and they are properly nested.

Example 1
  • Input: n = 3
  • Output: ["((()))", "(()())", "(())()", "()(())", "()()()"]
  • Explanation: For n = 3, we need to generate all valid combinations of 3 pairs of parentheses.
Example 2
  • Input: n = 2
  • Output: ["(())", "()()"]
  • Explanation: For n = 2, we need two pairs of parentheses. There are only two valid ways to arrange them.
Constraints
  • 1 <= n <= 8
  • The solution must generate all valid combinations without duplicates
  • Time Complexity: O(4^n / √n) - Catalan number
  • Space Complexity: O(n) for recursion stack, O(4^n / √n) for output storage
StringsBacktracking GoogleGoldman Sachs
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use backtracking to generate all valid combinations
  • Track the count of open and close parentheses used so far
  • You can add an open parenthesis if you haven't used all n yet
  • You can add a close parenthesis if the count of close parentheses is less than open parentheses
  • When both open and close counts reach n, you have a valid combination
  • Use an array to store all valid combinations

Steps to solve by this approach:

 Step 1: Create a backtracking function that builds combinations character by character.
 Step 2: Track two counters - the number of open and close parentheses used so far.
 Step 3: For each position, we have two choices: add '(' or add ')'.
 Step 4: We can add '(' if we haven't used all n opening parentheses yet.
 Step 5: We can add ')' only if there are more opening parentheses than closing ones.
 Step 6: When we've used all n pairs (2*n characters), we've found a valid combination.
 Step 7: Store each valid combination in our result array and continue backtracking.

Submitted Code :