You are given a number n. Build every string made of exactly n opening brackets ( and n closing brackets ) in which the brackets are properly matched.
Properly matched means each ) closes an earlier ( that is still open, and nothing is left open at the end. Return all such strings, in any order.
Example 1
Input: n = 2 Output: ["(())", "()()"] Why: the only two ways to match two pairs
1 more example and the constraints
Example 2
Input: n = 3 Output: ["((()))", "(()())", "(())()", "()(())", "()()()"] Why: five matched strings of length 6
Constraints
- 1 ≤ n ≤ 8
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Every string, then filterO(2²ⁿ · n)
- BacktrackingO(4ⁿ/√n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 8 | Verdict |
|---|---|---|---|
| Every string, then filter | O(2²ⁿ · n) | Passes at n = 8, but wasteful | |
| Backtracking | O(4ⁿ/√n) | Best; builds only valid strings |
n = number of bracket pairs. 2²ⁿ = 4ⁿ.
Edge cases to test
- n = 1. The answer is just
["()"]. - Closing too early. A string may never start with
); the rule closed < opened blocks it. - n = 8. 1,430 strings. The answer list itself is the biggest cost.
Common mistakes
- Allowing
)whenever closed < n instead of closed < opened, which builds strings like)(. - Mutating one shared string or list and saving a reference to it, so every saved answer changes later.
- Checking validity only at the end, which turns the backtracking back into the brute force.
How to talk through it
- 1Clarify. Only round brackets? Any order of the output? n is at least 1?
- 2Give the brute force. All 2²ⁿ strings, keep the balanced ones. Say why most of that work is wasted.
- 3State the two rules. Open while opened < n. Close while closed < opened. Those rules keep every partial string fixable.
- 4Code the recursion. Base case at length 2n, then the two guarded choices.
- 5Test out loud. Run n = 1 and n = 2 by hand and check you get 1 and 2 strings.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?