Skip to the code
cf.
+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 <= 8
  • 1 <= maxDepth <= 8
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

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