Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Coding problem

    Every balanced bracket string

    MediumAbout 25 minFull AccessLearn it: The universal backtracking template

    The task

    A test generator for a code formatter needs every correctly nested bracket string of a given size as input data.

    Complete BalancedBrackets(int pairs). Return every string of pairs opening brackets "(" and pairs closing brackets ")" in which, reading from the left, there are never more ")" than "(" so far. Return them in ascending ordinal order, where "(" comes before ")". 0 pairs give one string, the empty one. Throw ArgumentOutOfRangeException for a negative count.

    Signature

    public static List<string> BalancedBrackets(int pairs)

    Examples

    • 2 → ["(())", "()()"]. These are the only two ways to nest two pairs.
    • 0 → [""]. The empty string is the one way to write no pairs.

    Limits: Up to 12 pairs (208,012 strings).

    The tests check: 0, 1, 2, 3, 4 and 5 pairs, the order of the strings, every string balanced, 8 pairs, a negative count, and 12 pairs in time.

    Hints

      Your code

      C#Solution.csLoading the editor…

      Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;

      public static class Solution
      {
          // Every balanced string of `pairs` "(" and `pairs` ")", in ascending ordinal order.
          public static List<string> BalancedBrackets(int pairs)
          {
              throw new NotImplementedException();
          }
      }

      This problem comes with TechInterviewNotes Full Access

      Unlock all paid content on TechInterviewNotes.