DSA interview question
A code-formatting tool's test suite needs every well-formed arrangement of n pairs of parentheses, like (())() or ((())), to check that its parser handles all of them. A string is well formed if every ) closes an earlier unmatched ( and all of them are closed at the end. Instead of generating all 2²ⁿ strings and filtering, backtracking tracks two counters: an ( is allowed while fewer than n have been used, and a ) only while it has an unmatched ( to close.
Example: n = 3 → ((())) (()()) (())() ()(()) ()()().
vector<string> generateParenthesis(int n); // shown here in lexicographic order
Input n | Output | Explanation |
|---|---|---|
3 | ((())) (()()) (())() ()(()) ()()() | 5 strings |
1 | () | |
2 | (()) ()() | |
4 | 14 strings | The counts are Catalan numbers |
(Confirm: 1 ≤ n ≤ 8; any order is acceptable, and this solution produces lexicographic order because '(' sorts before ')'.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in