All Possible Braces
Problem Statement
Print all braces combinations for a given value n so that they are balanced. Here are a few examples:
Hint
- Recursion
Try it yourself
Solution
Solution Explanation
Runtime complexity
The runtime complexity of this solution is exponential,
Memory complexity
The memory complexity of this solution is linear, O(n).
Solution Breakdown
The solution is to maintain counts of left_braces and right_braces. The basic algorithm is as follows:
left_braces count: 0
right_braces count: 0
if left_braces count is less than n:
add left_braces and recurse further
if right_braces count is less than left_braces count:
add right_braces and recurse further
stop recursing when left_braces and right_braces counts are both equal to n
Practice problems like this and many more by checking out our Grokking the Coding Interview: Patterns for Coding Questions course!