Prepin
Log in

Create Parentheses

Approach / Explanation

The problem Generate Parentheses requires you to produce all possible combinations of valid parentheses for a specified number n . A valid parentheses string can be constructed in the following ways: starting with an empty string, using "()", or by combining "(" with a valid parentheses string followed by ")". Here are some key points to keep in mind: For a set of parentheses to be considered valid, each open parenthesis "(" must correspond to a closing parenthesis ")". A closing parenthesis ")" cannot appear without a preceding matching open parenthesis "(". The goal is to create all potential combinations rather than merely validating them. This problem is typically addressed through Depth-First Search (DFS) or Backtracking techniques.

Suggested Answer

Let's examine a scenario where n = 3 . One possible approach to tackle this issue using DFS is as follows: def generateParenthesis ( n ) : def generate ( p , left , right , parens = [ ] ) : if left : generate ( p + '(' , left - 1 , right ) if right > left : generate ( p + ')' , left , right - 1 ) if not right : parens . append ( p ) return parens return generate ( '' , n , n ) This code keeps track of the number of left and right parentheses remaining that can still be used. If there are left parentheses available to place at the current location, we insert one. If the count of right parentheses exceeds that of left parentheses, we can then add a closing parenthesis.

Alternative Answer

Another potential method to address this issue using the backtracking technique is as follows: def generateParenthesis ( n ) : result = [ ] def backtrack ( S = '' , left = 0 , right = 0 ) : if len ( S ) == 2 * n : result . append ( S ) return if left < n : backtrack ( S + '(' , left + 1 , right ) if right < left : backtrack ( S + ')' , left , right + 1 ) backtrack ( ) return result This code keeps track of the number of opening and closing parentheses used. If the number of opening parentheses '(' is less than n , we can add an '(' at the current position. Conversely, if the count of closing parentheses ')' is less than that of opening parentheses, we can add a ')' at the current position.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Google

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.