To find the maximum nesting depth of parentheses in a string, we need to understand what 'nesting' really means. It simply refers to how many parentheses are open at the same time at any point in the string.
Let's say we see an opening bracket (
— we increase our current depth by 1. When we see a closing bracket )
, we decrease the depth by 1. The maximum value that the current depth ever reaches is the maximum nesting depth.
For example, in the string (1+(2*3)+((8)/4))+1
, when we reach ((8)/4)
, we have three (
brackets opened before any are closed. So, the nesting depth there is 3, and that’s the deepest it ever gets.
If the string is something simple like 1+2
or abc
, there are no brackets, so the nesting depth is just 0.
Even in more complex-looking strings like (a+(b*(c+(d))))
, we ignore all characters except the brackets. The string reaches a depth of 4 due to four levels of parentheses before they start closing.
If the string is empty, or contains only characters without any (
or )
, then the answer is also 0 — there's no nesting at all.
What's great about this approach is that we don't need a stack. We just track how many parentheses are open as we scan left to right, and keep updating the maximum depth reached. It’s very efficient and runs in O(n) time.