1218. Kth Balanced Bracket String

A code generator wants to list well-formed bracket layouts in dictionary order without producing all of them. A balanced bracket string with n pairs has n opening brackets and n closing brackets, and every prefix has at least as many openings as closings. List all such strings in lexicographic order where ( comes before ). For n = 3 the order is ((())), (()()), (())(), ()(()), ()()().

Return the k-th string of that list, counting from 1, or the empty string "" when fewer than k strings exist. Count how many ways each partial string can be completed and choose the next character greedily instead of enumerating. Cap the counts at 2 * 10^15 so they stay exact even in JavaScript. The intended cost is O(n^2) time and space.

Example 1

Input:
n = 3, k = 1
Output:
"((()))"
Explanation:

The first string in dictionary order puts all openings first: ((())).

Example 2

Input:
n = 3, k = 3
Output:
"(())()"
Explanation:

The listing for three pairs reads ((())), (()()), (())(), so the third is (())().

Example 3

Input:
n = 3, k = 6
Output:
""
Explanation:

Only five strings exist for three pairs, so the sixth does not exist and the answer is the empty string.

Constraints

1 ≤ n ≤ 30

1 ≤ k ≤ 1015

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n^2)
Space
O(n^2)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…