Leetcode 1614. Maximum Nesting Depth of the Parentheses
The problem “1614. Maximum Nesting Depth of the Parentheses” requires to determine the maximum nesting depth of the parentheses in a given string s. A string is a valid parentheses string (VPS) if it meets any one of the following criteria:
AB (A concatenated with B), where A and B are valid parentheses strings.(A), where A is a valid parentheses string.Given a valid parentheses string s, the task is to return the maximum depth of nested parentheses.
s?
s is a valid parentheses string, so it will contain only ( and ) characters.To solve this problem, we’ll use a single pass traversal approach with a counter to keep track of the depth:
currentDepth to 0 and maxDepth to 0.( encountered, increment currentDepth. Update maxDepth whenever currentDepth exceeds the current maxDepth.) encountered, decrement currentDepth. It ensures correctly matching the nested depth by decrementing per closed parenthesis.maxDepth will hold the maximum depth of nested parentheses.public class Solution {
public int maxDepth(String s) {
// Initialize depth trackers
int currentDepth = 0;
int maxDepth = 0;
// Traverse the string
for (char ch : s.toCharArray()) {
if (ch == '(') {
currentDepth++;
if (currentDepth > maxDepth) {
maxDepth = currentDepth;
}
} else if (ch == ')') {
currentDepth--;
}
}
return maxDepth;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.maxDepth("(1+(2*3)+((8)/4))+1")); // Output: 3
System.out.println(sol.maxDepth("(1)+((2))+(((3)))")); // Output: 3
System.out.println(sol.maxDepth("1+(2*3)/(2-1)")); // Output: 1
System.out.println(sol.maxDepth("")); // Output: 0
}
}
The solution traverses the string once, processing each character in constant time O(1), so the time complexity is O(n), where n is the length of the string. The space complexity is O(1) since we are using a fixed amount of extra space for the counters.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?