oneby7

Strings Parentheses and nesting

134. Maximum Nesting Depth of the Parentheses

Easy

You are given a string s made of digits, the operators +, -, * and /, and parentheses, like a formula. Its parentheses are properly nested: every ( is closed by a later ), and every ) closes an earlier (.

Return the nesting depth of s: the largest number of pairs of parentheses that sit one inside the next. In (1+(2*3))+(4), the pair around 2*3 sits inside the first pair, so the depth is 2. A string with no parentheses has depth 0.

Example 1

Input: s = "(4+(2*(7-1)))/(3+5)"

Output: 3

Explanation: 7-1 sits inside three pairs: its own, the one around 2*(7-1), and the outer one. No character sits deeper.

Example 2

Input: s = "(1+2)*(3-4)/(5)"

Output: 1

Explanation: There are three pairs, but they sit side by side. None of them is inside another.

Example 3

Input: s = "8*3-1"

Output: 0

Explanation: There are no parentheses at all.

Check your understanding

Work out the answer for this input before you write any code.

s = "(1+(2)*(3+(4)))"

Constraints

  • 1 ≤ s.length ≤ 105
  • s holds only digits and the characters +, -, *, /, ( and ).
  • The parentheses in s are properly nested.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.