Balanced Parentheses

Hard40–60 pts depending on language · +25 for learning a language that's new to you

Return every balanced string you can make from n pairs of parentheses, in any order. Balanced means every ( is closed by a ) that comes after it, and no ) appears before its matching (.

generateParentheses(2) returns ["(())", "()()"].

This is a backtracking problem, like N-Queens: build the string one character at a time, and only add a character when the string can still end up balanced.

n is between 1 and 8.

Examples

Input: generateParentheses(2)

Output: ["(())", "()()"]

Input: generateParentheses(3)

Output: ["((()))", "(()())", "(())()", "()(())", "()()()"]

Your solution is checked against 2 example tests and 4 hidden tests (edge cases and bigger inputs).

Solved by 1 member

  1. 1CasonRust · Oct 20
Full leaderboard →

Your Solution

Languages you don't learn in class are worth more: C++ 1.25×, JavaScript, TypeScript, C, Rust and Go 1.5×. Your first solve in a language unlocks its "Learned" achievement: +25 for learning it.

Loading editor...

IntelliSense: connecting…

Run Code checks the example tests. Submit runs every test, including hidden ones.