Maximum Nesting Depth of the Parentheses

Given a valid parentheses string `s` (it may also contain digits and the operators `+ - * /`), return the nesting depth of `s`: the largest number of parentheses that are open at the same time.

30:00

Maximum Nesting Depth of the Parentheses
easy
Free written solution
Topics
Companies

Given a valid parentheses string s (it may also contain digits and the operators + - * /), return the nesting depth of s: the largest number of parentheses that are open at the same time.

Example 1:
Input: {"s":"(1+(2*3)+((8)/4))+1"}
Output: 3
Constraints:
  • 1≤s.length≤1001 \leq s.\text{length} \leq 100

  • s consists of digits 0-9 and the characters '+', '-', '*', '/', '(' and ')'.

  • It is guaranteed that the parentheses expression s is valid.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"(1+(2*3)+((8)/4))+1"}

depth while reading each character

(

0

1

1

+

2

(

3

2

4

*

5

3

6

)

7

+

8

(

9

(

10

8

11

)

12

/

13

4

14

)

15

)

16

+

17

1

18

Walk the string with a depth counter. Each "(" climbs one level, each ")" steps down, and best remembers the highest level reached.

depth (open right now)

0

best (deepest so far)

0

not reached yet

Variables
VariableValue
depth0
best0
DepthFunction Call
Stack empty
0/15