Dynamic programming · Medium
A parser test planner wants to count valid nesting structures containing a fixed number of parenthesis pairs. It needs the count only, not a list of strings. Generating every string would be unnecessary at the stated maximum size.
Count distinct balanced parenthesis strings containing exactly n opening and n closing parentheses.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ n: integer }
Fields
- n is the number of parenthesis pairs. A balanced string never has more closing than opening parentheses in any prefix.
Output
Return value
- Return one integer count, not the strings themselves.
- For n = 0, return one for the empty valid structure. Rotations and different nesting orders are distinct strings.
Constraints
- 0 <= n <= 20. Counts fit a safe JSON integer; 32-bit integer storage is insufficient.
Examples
Example 1
{
"n": 3
}Returns
5Example 2
{
"n": 1
}Returns
1Required complexity
O(n²) arithmetic operations and O(n) stored counts