Generate All Balanced Bracket Sequences for a Code Formatter Test

Last updated: November 29, 2026

Quick Overview

To fuzz a code formatter, generate every well-formed string of n pairs of round brackets. Return them all.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Phone Screen
Coding & Algorithms
Easy

0

0

0 solved


To fuzz a code formatter, generate every well-formed string of n pairs of round brackets. Return them all.

A familiar Google phone-screen problem used to test whether you can encode validity constraints directly in the recursion rather than generating and filtering. The interviewer checks the open/close counters and the Catalan-number count.

What the Interviewer Expects
  • Tracks open and close counts and only adds a valid next bracket
  • Never builds an invalid prefix, so no filtering pass is needed
  • Identifies the count as the n-th Catalan number
  • Gives complexity in terms of Catalan(n)
  • Handles n = 0
Key Topics to Cover
Backtracking
Catalan numbers
Constraint pruning
Recursion
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you extend this to three bracket types?
  • How would you return the k-th sequence in lexicographic order without generating all?
  • How would you count sequences for n = 1000 modulo a prime?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: integer n >= 0.
  • Output: all strings of length 2n with n ( and n ) where every prefix has at least as many ( as ).
  • Example: n = 3 gives ((())), (()()), (())(), ()(()), `()(...
High-Level Design

Build the string left to right while maintaining opened and closed counts.

  • We may add ( while opened < n.
  • We may add ) only while closed < opened, which keeps every prefix valid.

Whe...


Submit Your Answer
Markdown supported