← Deloitte bank

Deloitte · Question 39 · Backtracking

Generate Parentheses

BacktrackingJavacode⏱ O(4^n/sqrt(n))💾 O(n)
Service-based

Problem

Produce all well-formed parentheses strings of n pairs.

Approach

Backtracking with counts of open/close used.

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

How it works

  1. 1Open while opens remain.
  2. 2Close only while closes trail opens.

Sample input / output

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

Constraints

1 <= n <= 8.

Solution — read it, then walk it

Time O(4^n/sqrt(n))Space O(n)Branches 3Returns 2source · Java
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyesnoSTARTimport java.util.*DEFINE class MainDEFINE static List<String>generateParenthesis(int n)List<String> res = newArrayList<>()back(new StringBuilder(),0, 0, n, res)RETURN resDEFINE static voidback(StringBuilder sb, intopen, int close, int n…if (sb.length() == 2 *n)res.add(sb.toString())RETURNif (open < n)sb.append('(')back(sb, open + 1, close,n, res)sb.deleteCharAt(sb.length()- 1)if (close < open)sb.append(')')back(sb, open, close + 1,n, res)sb.deleteCharAt(sb.length()- 1)DEFINE static voidmain(String[] args)System.out.println(generateParenthesis(3))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/21

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