Advertisement

Generate Parentheses - LeetCode 22 Solution

Generate Parentheses - Complete Solution Guide

Generate Parentheses is LeetCode problem 22, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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

Detailed Explanation

The problem asks us to generate all possible combinations of well-formed (valid) parentheses given a number 'n' representing the number of pairs of parentheses. A well-formed parentheses string follows the rule that for any prefix of the string, the number of open parentheses must be greater than or equal to the number of close parentheses, and the total number of open and close parentheses must be equal to 'n' and 'n', respectively.

Solution Approach

The solution uses a backtracking algorithm. It maintains a stack (or string in C/C++) to build the parentheses string incrementally. At each step, it considers adding either an open or a close parenthesis. The conditions for adding each are crucial: we can only add an open parenthesis if the number of open parentheses is less than 'n', and we can only add a close parenthesis if the number of close parentheses is less than the number of open parentheses. When we have added 'n' open and 'n' close parentheses, we have a valid combination, and we add it to the result list. The stack is then popped to backtrack and try other possibilities.

Step-by-Step Algorithm

  1. Step 1: Initialize an empty list (res) to store the valid parentheses combinations.
  2. Step 2: Initialize an empty stack (or string) to build the current parentheses combination.
  3. Step 3: Define a recursive function backtrack(open_count, close_count).
  4. Step 4: Inside backtrack, check if open_count == n and close_count == n. If true, it means we have a valid combination. Add the current stack content to the result list and return.
  5. Step 5: If open_count < n, add an open parenthesis to the stack, increment open_count, and recursively call backtrack(open_count + 1, close_count). After the recursive call, remove the open parenthesis from the stack (backtracking step).
  6. Step 6: If close_count < open_count, add a close parenthesis to the stack, increment close_count, and recursively call backtrack(open_count, close_count + 1). After the recursive call, remove the close parenthesis from the stack (backtracking step).
  7. Step 7: Call backtrack(0, 0) to start the process.
  8. Step 8: Return the result list (res).

Key Insights

  • Insight 1: The core idea is to use backtracking. Backtracking allows us to explore all possible combinations by recursively adding either an open or a close parenthesis at each step, while ensuring we maintain the well-formed property.
  • Insight 2: We need to keep track of the number of open and close parentheses used so far. This is crucial for determining when to add an open parenthesis (only if open_count < n) or a close parenthesis (only if close_count < open_count).
  • Insight 3: The base case for the recursion is when both the number of open parentheses and the number of close parentheses are equal to 'n'. This means we have a valid combination, which can be added to our result set.

Complexity Analysis

Time Complexity: O(4^n/sqrt(n))

Space Complexity: O(4^n/sqrt(n))

Topics

This problem involves: String, Dynamic Programming, Backtracking.

Companies

Asked at: Adobe, Airtel, Amazon, Amdocs, Apple, Avito, BlackRock, Bloomberg, DE Shaw, Disney, Grammarly, Huawei, IBM, Infosys, Intuit, J.P. Morgan, Lucid, MakeMyTrip, Meta, Microsoft, Morgan Stanley, Netflix, Nvidia, Oracle, PhonePe, Point72, ServiceNow, Texas Instruments, TikTok, Uber, Veeva Systems, Walmart Labs, Yahoo, Yandex, Zenefits, Zoho, eBay, tcs.