PPractick

DSA interview question

Generate Parentheses

Medium · Algorithms · Topics: recursion, backtracking

The problem

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 → ((())) (()()) (())() ()(()) ()()().

Function signature

vector<string> generateParenthesis(int n);  // shown here in lexicographic order

Test cases

Input nOutputExplanation
3((())) (()()) (())() ()(()) ()()()5 strings
1()
2(()) ()()
414 stringsThe counts are Catalan numbers

(Confirm: 1 ≤ n ≤ 8; any order is acceptable, and this solution produces lexicographic order because '(' sorts before ')'.)

How interviewers phrase it

Clarifying questions to ask

  1. Only one type of bracket? (Yes.)
  2. Does the output order matter?
  3. How large can n be? (Up to 8: the output grows like the Catalan numbers.)

Follow-ups to expect

  1. "What are the two rules?"
  2. "Why never check validity at the end?"
  3. "How many results are there?"
  4. "Complexity?"
  5. "How would you check a string is valid?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in