Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Generate all parenthesis
MEDIUM
30 mins
22 upvotes
Strings
Topics (Covered in this problem)
Problem solved
Badge
Skill meter
Strings
-
-
Other topics
Problem solved
Badge
Skill meter
Matrices (2D Arrays)
-
-
Linked List
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Graph
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
Arrays
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
userLevel
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Generate all parenthesis

Contributed by
Arindam Majumder
Medium
yellow-spark
0/80
Avg time to solve 30 mins
Success Rate 85 %
Share
22 upvotes

Problem Statement

You are given an integer ‘N’, your task is to generate all combinations of well-formed parenthesis having ‘N’ pairs. You are task is to generate all possible valid sets of parenthesis that can be formed with a given number of pairs.

A parenthesis is called well-formed if it is balanced i.e. each left parenthesis has a matching right parenthesis and the matched pairs are well nested.

For Example:

For ‘N’ = 3,
All possible combinations are: 
((()))
(()())
(())()
()(())
()()()
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample Input 1:
2
Sample Output 1:
()()
(())
Explanation For Sample Output 1:
There are two possible combinations of parentheses:
()()
(())
Here both the parenthesis are balanced so the possible outputs can be [ [ ()() ],[ (()) ] ].
Sample Input 2:
4
Sample Output 2:
()()()()
()()(())
()(())()
()(()())
()((()))
(())()()
(())(())
(()())()
(()()())
(()(()))
((()))()
((())())
((()()))
(((())))
Reset Code
Full screen
Auto
copy-code
Console