Skip to content
BytePatterns

Balanced Bracket Strings

MediumBacktracking#backtracking#pruning~25m

Problem

Given a number of pairs n, return every string of n opening and n closing round brackets that is balanced: reading left to right, the closers seen so far never outnumber the openers seen so far. Return the strings in sorted order, where an opening bracket sorts before a closing one.

Examples

Input:  n = 3
Output: ["((()))", "(()())", "(())()", "()(())", "()()()"]
Input:  n = 1
Output: ["()"]
Input:  n = 0
Output: [""]
Why:    edge case, zero pairs still form one balanced string, the empty one

Hints

0 / 3

Stuck on the idea rather than the code? Backtracking covers it.