PPractick

DSA interview question

Maximum Nesting Depth of the Parentheses

Medium · Data structures · Topics: string, stack

The problem

A formula editor highlights how deeply nested each expression is, so users can spot overly complicated formulas. Given a valid expression like "(1+(2*3)+((8)/4))+1", it must report the maximum depth of nested parentheses: here 3, reached at (8). Since the expression is valid and there's only one bracket type, a running counter (increment on (, decrement on )) always equals the current depth, so the answer is simply the largest value the counter reaches.

Example: "(1+(2*3)+((8)/4))+1" → 3.

Function signature

int maxDepth(const string& s);  // s is a valid parentheses expression (may include digits and operators)

Test cases

Input sOutputExplanation
"(1+(2*3)+((8)/4))+1"3The 8 is inside three pairs
"(1)+((2))+(((3)))"3
"1+(2*3)/(2-1)"1
"1"0No parentheses
"()(())((()))"3

(Confirm: the input is a valid expression; characters other than parentheses are ignored.)

How interviewers phrase it

Clarifying questions to ask

  1. Is the string guaranteed to be valid?
  2. Are there other bracket types, like [ and {?
  3. Do other characters appear? (They're ignored.)

Follow-ups to expect

  1. "Why don't you need a stack?"
  2. "What if the string might be invalid?"
  3. "With several bracket types?"
  4. "Complexity?"

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