How deep does this nest
A config linter reports the deepest level of nested parentheses in an expression, because past a certain depth nobody can read it.
- Depth counts open parentheses that have not been closed yet.
- Text with no parentheses has a depth of zero.
- The input is well formed: every opener has its closer.
- Characters other than parentheses are ignored.
deepestNesting(expression: string) → int
Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
func deepestNesting(expression string) int {
}
Worked examples
| Call | Result |
|---|---|
deepestNesting("(1+(2*3)+((8)/4))+1") | 3 |
deepestNesting("(1)+((2))+(((3)))") | 3 |
deepestNesting("1+2") | 0 |
deepestNesting("") | 0 |
Hint
You do not need to store anything — a counter that rises on an opener and falls on a closer is a stack whose only interesting property is its height.
Reference solution in Go
func deepestNesting(expression string) int {
depth, deepest := 0, 0
for _, ch := range expression {
if ch == '(' {
depth++
if depth > deepest {
deepest = depth
}
} else if ch == ')' {
depth--
}
}
return deepest
}