LeetCode 22 Solution: Generate Parentheses

L

The LeetCode 22 Solution is centered around a classic coding problem that asks you to generate parentheses in all valid combinations, given a number n which represents pairs of parentheses. This problem tests your understanding of recursion, backtracking, and how to systematically construct balanced structures like parentheses.

In this blog post, we will explore how to solve this problem efficiently using a backtracking approach, walk through the solution step-by-step, and discuss why this method works well for generating valid parentheses.

Problem Overview: Generate Parentheses

The task is simple to understand but tricky to implement correctly. You are given an integer n, which is the number of pairs of parentheses. For example, when n = 3, you are required to generate all the valid combinations of three pairs of well-formed parentheses.

For example, when n = 3, the valid combinations are:

  • ((()))
  • (()())
  • (())()
  • ()(())
  • ()()()

These are just five possible combinations. Each string is considered valid if every opening parenthesis ( has a corresponding closing parenthesis ), and at no point does a closing parenthesis appear before a matching opening one.

The Challenge of Generating Valid Parentheses

The challenge lies in ensuring that you only create valid combinations of parentheses. It’s tempting to try a brute-force solution that generates every possible sequence of n opening and n closing parentheses and then filter out the valid ones. However, this approach is inefficient because the number of invalid combinations grows rapidly as n increases.

Instead, a more efficient solution is to use backtracking, where you build the string one character at a time and ensure that at every step, the sequence remains valid.

High-Level Approach: Backtracking

Backtracking is a technique that involves exploring all possible options but abandoning paths that won’t lead to a solution early on. In the case of the generate parentheses problem, we maintain two counters:

  • One for the number of opening parentheses added (().
  • Another for the number of closing parentheses added ()).

The core idea is that:

  1. We can only add an opening parenthesis if the total number of opening parentheses used so far is less than n.
  2. We can only add a closing parenthesis if the number of closing parentheses used is less than the number of opening ones.

By following these two rules, we ensure that we always build valid combinations and discard invalid ones early on, avoiding unnecessary work.

Backtracking Solution in Python

Let’s dive into the Python implementation of the backtracking approach for this LeetCode 22 solution.

def generateParenthesis(n: int):
    result = []

    def backtrack(current, open_count, close_count):
        if len(current) == 2 * n:
            result.append(current)
            return

        if open_count < n:
            backtrack(current + '(', open_count + 1, close_count)

        if close_count < open_count:
            backtrack(current + ')', open_count, close_count + 1)

    backtrack('', 0, 0)
    return result

How the Solution Works

The solution revolves around a recursive helper function called backtrack. This function builds the valid parentheses string one step at a time. It takes three parameters:

  • current: The current state of the parentheses string being built.
  • open_count: How many opening parentheses have been added so far.
  • close_count: How many closing parentheses have been added so far.

The recursive function checks:

  • If the length of the current string is equal to 2 * n (meaning all parentheses have been used), we add it to the result list.
  • If we can still add more opening parentheses (i.e., open_count < n), we recursively add an opening parenthesis (.
  • If we can add more closing parentheses (i.e., close_count < open_count), we recursively add a closing parenthesis ).

By following this approach, we ensure that every valid combination is generated and invalid combinations are pruned early on.

Time and Space Complexity

The time complexity of this solution is related to the Catalan number sequence, which counts the number of valid parentheses combinations for a given n. The time complexity is approximately (O(4n / sqrt{n})). This reflects the number of valid combinations we need to generate.

In terms of space complexity, we need to store the combinations and use a recursion stack. This gives us a space complexity of approximately (O(4n / sqrt{n})), similar to the time complexity.

Why Backtracking is Ideal for Generate Parentheses

Backtracking is an ideal approach for the generate parentheses problem because it allows us to avoid unnecessary computation. By carefully managing the number of open and close parentheses, we only generate valid combinations from the start, rather than generating all possibilities and filtering them later.

For example, if we try to add a closing parenthesis before an opening parenthesis has been added, the recursion stops, and we avoid exploring that invalid path. This “pruning” behavior makes backtracking both efficient and elegant.

Conclusion

The LeetCode 22 solution to the generate parentheses problem is an excellent exercise in recursion and backtracking. By leveraging the properties of well-formed parentheses, we can systematically build all valid combinations without wasting time on invalid ones.

If you’re preparing for technical interviews or want to improve your problem-solving skills, understanding this problem and the backtracking technique is crucial. It helps you learn how to explore solution spaces efficiently and is widely applicable in many other algorithmic problems.

By mastering this problem, you’ll gain a solid grasp of how to think recursively and solve complex problems step-by-step, which is a valuable skill in competitive programming and real-world coding challenges.

Happy Coding!


Looking for more LeetCode solutions? Stay tuned for upcoming guides on tackling other LeetCode challenges in Python. Whether you’re preparing for technical interviews or aiming to improve your coding skills, exploring a variety of problems will enhance your understanding and proficiency.

You can find this problem on LeedCode, click here.

1 comment

By Peter

About me

Hi, I’m Peter, a professional developer with over 25 years of experience. My journey with coding started when I was just a kid, exploring the world of programming and building my first projects out of pure curiosity and passion. Since then, I’ve turned this lifelong passion into a rewarding career, working on a wide range of projects, from small scripts to complex applications.

Now, I’m here to help others get started with coding through this blog. I know that learning to code can feel overwhelming at first, but I believe that with the right guidance, anyone can develop the skills they need to become a proficient programmer. My goal is to simplify the learning process and provide step-by-step resources that make coding accessible, fun, and practical for everyone.

Whether you’re just starting out or looking to sharpen your skills, I hope this blog serves as a valuable resource on your coding journey. Let’s dive into Python together!

Get in touch

Have any questions or feedback? Feel free to reach out—I’m always happy to help you on your coding journey!

Tags