CodingNodes / Stack / Generate Parentheses System design Space play · ←→ step · R restart

Problem

Given a whole number n, list every string made of exactly n opening brackets ( and n closing brackets ) that is balanced.

Balanced means that reading left to right, the number of ) seen so far never exceeds the number of ( seen so far, and the two counts are equal at the end. The strings may be returned in any order.

Constraints

  • 1 ≤ n ≤ 8

Examples: pick one to animate

Solutions

TimeO(4ⁿ / √n) SpaceO(n)

Time: The number of answers is the n-th Catalan number, about 4ⁿ divided by n to the power 1.5. The count rules mean every branch we enter leads to at least one answer, so the work is the number of answers times the length 2n of each, which is O(4ⁿ / √n).

Space: Besides the output, the recursion is at most 2n calls deep and the path holds at most 2n characters.

Build the string left to right. An open bracket is allowed while fewer than n have been used. A close bracket is allowed only while there are more opens than closes. Those two rules never create a dead end, so every full-length path is a valid answer.