Taro Logo

Generate Parentheses

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+29
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.8K views
Topics:
RecursionStrings

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

Example 1:

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2:

Input: n = 1
Output: ["()"]

Constraints:

  • 1 <= n <= 8

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum value of $n$ we can expect, and are there any specific memory or time limits I should design for?
  2. What should the function return if $n$ is 0? Should it be an empty list, or a list containing an empty string?
  3. Does the order of the generated combinations in the output list matter, or can they be returned in any order?
  4. Can we assume the input $n$ will always be a non-negative integer?
  5. Should the output contain any duplicate combinations, or are all generated valid combinations guaranteed to be unique?

Brute Force Solution

Approach

When you need to create all possible combinations of opening and closing parentheses for a given number of pairs, the brute force approach is to write down every single possible combination of the correct length. Once you have generated all of those possibilities, you go through them one by one and throw away any combination that does not make grammatical sense.

Here's how the algorithm would work step-by-step:

  1. Figure out the total number of opening and closing symbols you need to use based on the given pair count.
  2. Write down every conceivable arrangement of those symbols, just like writing out every possible word you can make with a set of letters.
  3. Include even the messy combinations where closing symbols appear before opening symbols.
  4. Go through your massive list of combinations one by one.
  5. Test each combination to see if every opening symbol is properly closed in the right order.
  6. Keep only the combinations that pass the test and discard the rest.

Code Implementation

def generateParenthesis(pair_count):
    total_length = pair_count * 2

    # Generate every single permutation of opening and closing characters
    def generate_all_combinations(current_string):
        if len(current_string) == total_length:
            return [current_string]
        
        return generate_all_combinations(current_string + '(') + generate_all_combinations(current_string + ')')

    all_possibilities = generate_all_combinations('')

    # Verify grammatical correctness by tracking nesting depth balance
    def is_combination_valid(candidate):
        nesting_balance = 0
        for symbol in candidate:
            if symbol == '(':
                nesting_balance += 1
            else:
                nesting_balance -= 1
            
            if nesting_balance < 0:
                return False
        
        return nesting_balance == 0

    valid_combinations = []

    # Filter the massive list to retain only grammatically sound strings
    for candidate_string in all_possibilities:
        if is_combination_valid(candidate_string):
            valid_combinations.append(candidate_string)

    return valid_combinations

Big(O) Analysis

Time Complexity
O(n * 2^(2n)) – The input size n represents the number of parenthesis pairs, meaning we must generate every conceivable arrangement of 2n symbols, resulting in 2^(2n) total possible combinations. For each of these generated strings, we spend O(n) time validating whether it is a well-formed combination of parentheses. Multiplying the total number of candidates by the validation cost gives approximately n * 2^(2n) operations, which simplifies to O(n * 2^(2n)).
Space Complexity
O(4^n / sqrt(n)) – To analyze the auxiliary space, we must account for both the recursion stack and the output list storing the valid combinations. The recursion depth reaches a maximum of 2N because we place N opening and N closing parentheses. Additionally, the number of valid combinations generated scales with the nth Catalan number, which grows exponentially relative to the input size N. Therefore, storing all valid strings in the final result dominates the space complexity alongside the memory consumed by the active stack frames during generation.

Optimal Solution

Approach

Instead of blindly guessing every possible combination of parentheses, the optimal approach builds valid sequences step by step by making smart choices. It ensures the resulting string is always structurally sound by tracking how many opening and closing symbols are still available to place.

Here's how the algorithm would work step-by-step:

  1. Imagine you have a blank slate and a specific number of opening and closing parentheses to place.
  2. You can always add an opening parenthesis as long as you still have some left in your supply.
  3. You can only add a closing parenthesis if you have already placed more opening parentheses than closing ones, ensuring everything stays properly matched.
  4. Continue making these careful choices until you run out of all parentheses.
  5. Whenever you successfully use up all your supplies, you have discovered a complete, perfectly balanced combination.
  6. By following these strict rules at every single decision point, you naturally skip all broken combinations and only generate the valid ones.

Code Implementation

class Solution:
    def generateParenthesis(self, pair_count: int) -> list[str]:
        valid_combinations = []

        def backtrack(current_string, open_count, close_count):
            if len(current_string) == pair_count * 2:
                valid_combinations.append(current_string)
                return

            # We can always add an opening parenthesis as long as we have some left.
            if open_count < pair_count:
                backtrack(current_string + '(', open_count + 1, close_count)

            # Closing parentheses can only be added if they do not exceed open ones.
            if close_count < open_count:
                backtrack(current_string + ')', open_count, close_count + 1)

        backtrack('', 0, 0)
        # Returning the list guarantees all perfectly balanced combinations are outputted.
        return valid_combinations

Big(O) Analysis

Time Complexity
O(4ⁿ / √(n)) – The time complexity is driven by the number of valid parenthesis combinations generated, which grows exponentially according to the nth Catalan number. For a given n, the algorithm explores a decision tree of height 2n where each valid leaf represents a complete sequence of length 2n. Because the number of valid sequences tightly bounds the total operations performed across all recursive branches, the work scales asymptotically with the nth Catalan number. This total execution cost approximates 4 to the power of n divided by the square root of n, which simplifies to the tight Big O bound of O(4ⁿ / √(n)).
Space Complexity
O(n) – The auxiliary space is primarily consumed by the recursion stack used to build the parentheses step by step. Since each valid combination requires placing two times n characters, the maximum depth of the recursive calls reaches 2n at any given time. Additionally, the temporary string builder or path variable holds at most 2n characters during each phase of construction. Therefore, the extra memory scales linearly with the input size n, culminating in an overall auxiliary space complexity of O(n) excluding the final output storage.

Edge Cases

Input n equals zero
How to Handle:
The recursive backtracking function should immediately return a list containing a single empty string.
Input n equals one
How to Handle:
The algorithm builds and returns the only possible valid combination which is a single pair.
Maximum expected constraints such as n equals eight
How to Handle:
Backtracking naturally scales within acceptable time limits and prevents generating invalid permutations upfront.
Deep recursion depth for larger values of n
How to Handle:
The call stack depth reaches 2n, which is safely within standard system stack limits for expected constraints.
Preventing invalid prefix strings during generation
How to Handle:
The algorithm enforces the invariant that close count never exceeds open count at any recursive step.
Ensuring all valid combinations are uniquely generated
How to Handle:
By strictly branching on available open and close counts, we avoid generating duplicates entirely.
Negative values of n
How to Handle:
Constraint validation at the entry point should check for non-negative integers and return an empty list.
Memory limits due to large output size
How to Handle:
Since the total output scales with the Catalan number C_n, memory consumption grows exponentially and must fit within heap limits.
0/75 completed