← Capgemini bank

Capgemini · Question 36 · Backtracking

Generate Parentheses

BacktrackingC++code⏱ O(4^n/√n)💾 O(n)
Service-based

Problem

You are given n pairs of parentheses. Generate all combinations of well-formed parentheses.

Approach

Backtrack adding '(' while opens remain and ')' while closes trail opens.

Time O(4^n/√n)Space O(n)

How it works

  1. 1Track remaining open and close brackets.
  2. 2Close only when closes trail opens.

Sample input / output

Input:
n = 3
Output:
[((())), (()()), (())(), ()(()), ()()()]

Constraints

1 <= n <= 8.

Solution — read it, then walk it

Time O(4^n/√n)Space O(n)Loops 1Branches 4Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyesno↻ repeatSTARTinclude <iostream>include <string>include <vector>using namespace stdDEFINE generate(int open,int close, string current,vector<string>& result)if (open == 0 && close== 0)result.push_back(current)RETURNif (open > 0)generate(open - 1, close,current + "(", result)if (close > open)generate(open, close - 1,current + ")", result)vector<string>generateParenthesis(int n)DEFINE main()auto r =generateParenthesis(3)cout << "["for (size_t i = 0; i <r.size(); ++i)if (i) cout << ", "cout << r[i]cout << "]" << endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/22

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits