Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 900433
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T15:23:12+00:00 2026-05-15T15:23:12+00:00

Possible Duplicate: Solution to a recursive problem (code kata) give an algorithm to find

  • 0

Possible Duplicate:
Solution to a recursive problem (code kata)

give an algorithm to find all valid permutation of parenthesis for given n
for eg :

for n=3, O/P should be
{}{}{} 
{{{}}}
{{}}{} 
{}{{}} 
{{}{}}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T15:23:12+00:00Added an answer on May 15, 2026 at 3:23 pm

    Overview of the problem

    This is a classic combinatorial problem that manifests itself in many different ways. These problems are essentially identical:

    • Generating all possible ways to balance N pairs of parentheses (i.e. this problem)
    • Generating all possible ways to apply a binary operator to N+1 factors
    • Generating all full binary trees with N+1 leaves
    • Many others…

    See also

    • Wikipedia/Catalan number
    • On-Line Encyclopedia of Integer Sequences/A000108

    A straightforward recursive solution

    Here’s a simple recursive algorithm to solve this problem in Java:

    public class Parenthesis {
        static void brackets(int openStock, int closeStock, String s) {
            if (openStock == 0 && closeStock == 0) {
                System.out.println(s);
            }
            if (openStock > 0) {
                brackets(openStock-1, closeStock+1, s + "<");
            }
            if (closeStock > 0) {
                brackets(openStock, closeStock-1, s + ">");
            }
        }
        public static void main(String[] args) {
            brackets(3, 0, "");
        }
    }
    

    The above prints (as seen on ideone.com):

    <<<>>>
    <<><>>
    <<>><>
    <><<>>
    <><><>
    

    Recursion Tree for n=3

    Essentially we keep track of how many open and close parentheses are “on stock” for us to use as we’re building the string recursively.

    • If there’s nothing on stock, the string is fully built and you can just print it out
    • If there’s an open parenthesis available on stock, try and add it on.
      • Now you have one less open parenthesis, but one more close parenthesis to balance it out
    • If there’s a close parenthesis available on stock, try and add it on.
      • Now you have one less close parenthesis

    Note that if you swap the order of the recursion such that you try to add a close parenthesis before you try to add an open parenthesis, you simply get the same list of balanced parenthesis but in reverse order! (see on ideone.com).


    An “optimized” variant

    The above solution is very straightforward and instructive, but can be optimized further.

    The most important optimization is in the string building aspect. Although it looks like a simple string concatenation on the surface, the above solution actually has a “hidden” O(N^2) string building component (because concatenating one character to an immutable String of length N is an O(N) operation). Generally we optimize this by using a mutable StringBuilder instead, but for this particular case we can also simply use a fixed-size char[] and an index variable.

    We can also optimize by simplifying the recursion tree. Instead of recursing “both ways” as in the original solution, we can just recurse “one way”, and do the “other way” iteratively.

    In the following, we’ve done both optimizations, using char[] and index instead of String, and recursing only to add open parentheses, adding close parentheses iteratively: (see also on ideone.com)

    public class Parenthesis2 {
        public static void main(String[] args) {
            brackets(4);
        }
        static void brackets(final int N) {
            brackets(N, 0, 0, new char[N * 2]);
        }
        static void brackets(int openStock, int closeStock, int index, char[] arr) {
            while (closeStock >= 0) {
                if (openStock > 0) {
                    arr[index] = '<';
                    brackets(openStock-1, closeStock+1, index+1, arr);
                }
                if (closeStock-- > 0) {
                    arr[index++] = '>';
                    if (index == arr.length) {
                        System.out.println(arr);
                    }
                }
            }
        }
    }
    

    The recursion logic is less obvious now, but the two optimization techniques are instructive.


    Related questions

    • Checking string has balanced parentheses
    • Basic Recursion, Check Balanced Parenthesis
    • The possible number of binary search trees that can be created with N keys is given by the Nth catalan number. Why?
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 506k
  • Answers 506k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Try: update T set A=1 where A != 2 or… May 16, 2026 at 3:46 pm
  • Editorial Team
    Editorial Team added an answer Try this: from pylons import config print config['pylons.paths']['root'] May 16, 2026 at 3:46 pm
  • Editorial Team
    Editorial Team added an answer Access tokens are granted per APP ID, not per domain… May 16, 2026 at 3:46 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

Possible Duplicates: Is there a problem that has only a recursive solution? Can every
Possible Duplicate: How costly is .NET reflection? The elegant solution to a problem I
Possible Duplicate: Project Euler, Problem 10 java solution not working So, I'm attempting to
Possible Duplicate: How do you give a C# Auto-Property a default value? Hi all:
Possible Duplicate: What is the best solution to replace a new memory allocator in
Possible Duplicate: HTML table with fixed headers? Looking for a solution to create a
Possible Duplicate: How does this work? Weird Towers of Hanoi Solution While surfing Google,
Possible Duplicate: How do you count the lines of code in a Visual Studio
Possible Duplicate: Change the Target Framework for all my projects in a Visual Studio
Possible Duplicate: Plain English explanation of Big O I can't find any sufficient help

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.