00:00

Problem Statement

Input/Output Examples

Visual Explanation

The two rules prune every branch that would produce an invalid string. As a result, the work done is proportional to the number of valid answers, not to all 22n bracket strings.

Approaches

Backtracking builds strings character by character. The dynamic-programming approach builds them from smaller answers.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

The number of valid strings is the n-th Catalan number, about 4n / (n √n), and each has length 2n. Any correct solution must produce all of them.

Interview Tips and Recommended Approach

  • State the two rules. open < n to add (; close < open to add ).
  • Avoid generate-then-filter. Building all 22n strings and checking each wastes work on invalid ones.
  • Mention the Catalan numbers. 1, 1, 2, 5, 14, 42, … is a strong signal you understand the structure.
  • Reuse one builder. Appending and deleting on a shared StringBuilder keeps memory at O(n).

Recommended Approach: Backtracking With Counts

Why: it never creates an invalid string, keeps only the current path in memory and produces the results already sorted.