↓Skip to main content
  1. LeetCode/

LeetCode 22: Generate Parentheses

·2 mins· ·
LeetCode Daily Medium String Backtracking Recursion Combinatorics Parentheses
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: Medium First Attempt: 2025-08-10

  • Total time: 00:00.00

Intuition
#

This is a backtracking problem where we need to generate all valid parentheses combinations. The key insight is to ensure that the right parenthesis count is always less than or equal to the left parenthesis count in the remaining available positions. This constraint guarantees that we only generate valid parentheses strings.

Approach
#

The solution uses a backtracking approach with the following key constraints:

  1. Left parenthesis constraint: We can add a left parenthesis if left > 0
  2. Right parenthesis constraint: We can add a right parenthesis only if right > left (ensuring validity)
  3. Base case: When both left and right reach 0, we have a complete valid string

The backtracking function tracks:

  • left: remaining left parentheses to place
  • right: remaining right parentheses to place
  • s: current string being built
class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        res = []

        def backtracking(left, right, s):

            nonlocal res

            if left == 0 and right == 0:
                res.append(s)
                return
            
            if left > 0:
                backtracking(left - 1, right, s + "(")
            if right > left:
                backtracking(left, right - 1, s + ")")

        backtracking(n, n, "")

        return res

Time Complexity: O(4^n/√n) - Catalan number growth Space Complexity: O(n) for the recursion stack

Findings
#

  • Backtracking efficiency: This approach efficiently generates all valid combinations without duplicates
  • Constraint-based pruning: The right > left condition ensures we never generate invalid parentheses strings
  • Catalan numbers: The number of valid parentheses combinations follows the Catalan number sequence
  • Recursive structure: The problem naturally fits a recursive solution due to its combinatorial nature

Encountered Problems
#

Related

LeetCode 20: Valid Parentheses
·2 mins
LeetCode Daily Easy String Stack Data-Structures Parentheses Validation
Solving the Valid Parentheses problem using stack-based approach
LeetCode 1456: Maximum Number of Vowels in a Substring of Given Length
·2 mins
LeetCode Daily Medium String Sliding-Window Fixed-Window Vowel-Counting
LeetCode Problem Solving - Fixed Size Sliding Window with Vowel Counting
LeetCode 438: Find All Anagrams in a String
·4 mins
LeetCode Daily Medium String Sliding-Window Hash-Map Anagram Frequency-Counting
LeetCode Problem Solving - Sliding Window with Character Frequency
LeetCode 567: Permutation in String
·4 mins
LeetCode Daily Medium String Sliding-Window Hash-Map Frequency-Counting Permutation
LeetCode Problem Solving - Sliding Window with Character Frequency
LeetCode 988: Smallest String Starting From Leaf
·1 min
LeetCode Medium String Backtracking Tree Depth-First-Search
LeetCode 988 note: DFS prepending each character so the string at a leaf already reads leaf to root, and keep the smallest
LeetCode 93: Restore IP Addresses
·2 mins
LeetCode Medium String Backtracking
LeetCode 93 note: cut into exactly 4 pieces, each 1 to 3 digits long, valued 0 to 255, with no leading zero except 0 itself