Skip to the code
+25 XP

#288 Balanced Bracket Snippets

medium

A code editor's test suite needs sample snippets made of brackets. A snippet uses exactly n pairs of ( and ) and must be balanced: reading left to right, there are never more ) than ( so far, and the totals are equal at the end.

The editor's linter also rejects nesting deeper than maxDepth. The depth at a point is the number of ( opened and not yet closed.

Write balancedSnippets(n, maxDepth) that returns every balanced snippet with n pairs whose depth never goes above maxDepth, sorted ascending (( sorts before )).

Example 1

Input: n = 3, maxDepth = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

With depth up to 3 allowed, all five balanced snippets of 3 pairs are valid.

Example 2

Input: n = 3, maxDepth = 1
Output: ["()()()"]

With depth 1, every ( must close before the next one opens.

Constraints

  • 1 <= n <= 18
  • 1 <= maxDepth <= 18
  • The answer holds at most 150,000 snippets.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).