Skip to content
CodeKruPro

Generate balanced brackets up to a depth limit

Coding problemMedium

Given whole numbers n and depth, return every string of n opening brackets ( and n closing brackets ) that is balanced and never nests deeper than depth.

Balanced means every closing bracket closes an earlier opening one, and every opening bracket is closed. The nesting depth at a point is the number of brackets open there; "(())" reaches depth 2 and "()()" stays at depth 1. When depth is at least n, the limit never matters and you get every balanced string. Return the strings in any order.

Examples

Example 1
Input: n = 3, depth = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2
Input: n = 3, depth = 2
Output: ["(()())","(())()","()(())","()()()"]
"((()))" reaches depth 3, so it is left out.
Example 3
Input: n = 2, depth = 1
Output: ["()()"]

Constraints

  • 1 <= n <= 10
  • 1 <= depth <= 10

Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.

Run your code to see the results here.

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in