Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
Run through a set of example cases:
HAPPY CASE
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Input: n = 1
Output: ["()"]
EDGE CASE
Input: n = 0
Output: [""]
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Instead of adding '(' or ')' every time, let's only add them when we know it will remain a valid sequence. We can do this by keeping track of the number of opening and closing brackets we have placed so far.
1) create a list that will store the result
2) call our backtracking function with empty string and initial number of opening and closing parentheses
3) check the base case. If number of opening and closing parentheses are equal to n then we will add the string to the list and return.
4) if the base case does not meet then we will check if number of opening parentheses is less than n, If true, then we will add ( to the current string and increment the count of opening parenthesis.
5) check if number of closing parentheses is less than open parentheses then we will add ) to the current string and increment the count of closing parentheses.
⚠️ Common Mistakes
From the problem's description, recursion seems like the way to go. However, this naive approach is to generate all the permutations. All sequence of length n is ( plus all sequences of length n - 1. The time complexity of this will be O(2 to the nth power) which is quite large.
Implement the code to solve the algorithm.
class Solution:
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
OPEN = '('
CLOSE = ')'
def gen(combo, open_count, close_count, n, res):
# we have generated all open and close parens, add combo to result
if open_count == close_count == n:
# when n == 0
if combo != '':
res.append(combo)
# used all opens, must close
elif open_count == n:
gen(combo + CLOSE, open_count, close_count + 1, n, res)
# current pairs all closed, must open before another close
elif open_count == close_count:
gen(combo + OPEN, open_count + 1, close_count, n, res)
# otherwise, free to open or close
else:
gen(combo + OPEN, open_count + 1, close_count, n, res)
gen(combo + CLOSE, open_count, close_count + 1, n, res)
res = []
gen('', 0, 0, n, res)
return res:
class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<String>();
generateParenthesis(n, n, result, "");
return result;
}
private void generateParenthesis(int left, int right, List<String> result,
String currString){
if(left == 0 && right == 0){
result.add(currString);
return;
}
if(left == right || (left < right && left > 0)){
// we open a bracket
generateParenthesis(left - 1, right, result, currString + "(");
if(left == 0) return;
if(left == right) return;
// time to close the remaining opened bracket n - 1 left
else generateParenthesis(left, right - 1, result, currString + ")");
}
else if(left == 0 && right > left){
// we close a bracket
generateParenthesis(left, right - 1, result, currString + ")");
if(left == 0) return;
// time to close the remaining opened bracket n - 1 left
else generateParenthesis(left, right - 1, result, currString + ")");
}
}
}
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
The complexity analysis based on how many elements there are in generateParenthesis(n).