logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
13. Roman to Integer14. Longest Common Prefix20. Valid Parentheses26. Remove Duplicates from Sorted Array35. Search Insert Position69. Sqrt(x)70. Climbing Stairs88. Merge Sorted Array (In-Place)104. Maximum Depth of Binary Tree118. Pascal's Triangle121. Best Time to Buy and Sell Stock205. Isomorphic Strings242. Valid Anagram283. Move Zeroes345. Reverse Vowels of a String605. Can Place Flowers704. Binary Search796. Rotate String1071. Greatest Common Divisor of Strings1299. Replace Elements with Greatest Element on Right Side1431. Kids With the Greatest Number of Candies1614. Maximum Nesting Depth of the Parentheses1752. Check if Array Is Sorted and Rotated1768. Merge Strings Alternately1903. Largest Odd Number in String2965. Find Missing and Repeated Values
Code Scratch/leetcode/easy

1614. Maximum Nesting Depth of the Parentheses

1 min read
On this pageIntuition
IntuitionComplexityCode

# Intuition

We want to find how deeply nested the parentheses go in a valid string. We can track this by incrementing a depth counter when we see '(', and decrementing it when we see ')'.
At every step, we update the maximum depth seen so far.

# Complexity

Space ComplexityTime Complexity
O(1)\text{O}(1)O(1)O(N)\text{O}(N)O(N)

# Code

public int maxDepth(String parenthesesString) {
    int currentDepth = 0;     // Tracks current depth as we parse
    int maxDepthSeen = 0;     // Tracks the maximum depth encountered
 
    // Traverse each character in the input string
    for (int i = 0; i < parenthesesString.length(); ++i) {
        char currentChar = parenthesesString.charAt(i);
 
        // When we open a parenthesis, increase the depth
        if (currentChar == '(') {
            currentDepth++;
        } 
        // When we close a parenthesis, decrease the depth
        else if (currentChar == ')') {
            currentDepth--;
        }
 
        // Update the max depth seen so far
        maxDepthSeen = Math.max(maxDepthSeen, currentDepth);
    }
 
    return maxDepthSeen; // Return the deepest nesting level
}
 
←Previous1431. Kids With the Greatest Number of CandiesNext→1752. Check if Array Is Sorted and Rotated

On this page

IntuitionComplexityCode