Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Maximum Nesting Depth of Parentheses



Problem Statement

Given a valid parentheses string s, your task is to find the maximum nesting depth of parentheses in the string.

Return 0 if the string is empty or contains no parentheses.

Examples

Input StringMaximum Nesting DepthDescription
"(1+(2*3)+((8)/4))+1"3Deepest level is ((8)/4) → depth 3
"(1)+((2))+(((3)))"3Increasing levels of nested brackets
"1+(2*3)/(2-1)"1Only one pair of parentheses at a time
"1+2-3"0No parentheses present
""0Empty string returns 0
"(()(()))"3Nested parentheses with maximum 3 levels
"(a+(b*(c+(d))))"4Characters ignored, structure leads to depth 4

Solution

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.

Visualization

Algorithm Steps

  1. Initialize two variables: depth = 0 and maxDepth = 0.
  2. Loop through each character ch in the string s.
  3. If ch == '(', increment depth and update maxDepth if depth > maxDepth.
  4. If ch == ')', decrement depth.
  5. Return maxDepth at the end.

Code

Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
def max_depth(s):
    depth = 0
    max_depth = 0
    for ch in s:
        if ch == '(':
            depth += 1               # Increase current depth
            max_depth = max(max_depth, depth)  # Update max if needed
        elif ch == ')':
            depth -= 1               # Decrease depth on closing bracket
    return max_depth

# Sample input
print(max_depth("(1+(2*3)+((8)/4))+1"))  # Output: 3

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)We must scan every character once, even if there are few or no parentheses.
Average CaseO(n)Each character is checked, and counters are updated accordingly.
Average CaseO(n)Even with maximum depth and complexity, each character is visited once.

Space Complexity

O(1)

Explanation: Only a few counters are used. No extra data structures like stacks are required.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M