Skip to content

Instantly share code, notes, and snippets.

@gsrai
Last active May 20, 2022 13:39
Show Gist options
  • Save gsrai/94c2404bd7c0409ec7f66813fa88131c to your computer and use it in GitHub Desktop.
Save gsrai/94c2404bd7c0409ec7f66813fa88131c to your computer and use it in GitHub Desktop.
Maximum Nesting Depth of the Parentheses in python, java, clojure, javascript and go
def max_depth(s):
arr = [0]
for char in s:
if char == "(":
arr.append(arr[-1] + 1)
if char == ")":
arr.append(arr[-1] - 1)
return max(arr)
s = "( ((X)) (((Y))) )"
result = max_depth(s)
print(result)
;; Contest: 210
;; Problem Name: Maximum Nesting Depth of the Parentheses
;; Problem Link: https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/
(defn max-depth [s]
(->> s
(re-seq #"[()]")
(map #(if (= % "(") 1 -1))
(reductions +)
(apply max)))
;; even more terse
(defn max-depth [s]
(->> s
(keep { \( 1 \) -1 })
(reductions +)
(apply max)))
(max-depth "( ((X)) (((Y))) )")
// source: https://www.geeksforgeeks.org/find-maximum-depth-nested-parenthesis-string/
//Java program to find the maximum depth of nested
// parenthesis in a given expression
class GFG {
static int maxDepth(String S) {
int current_max = 0; // current count
int max = 0; // overall maximum count
int n = S.length();
// Traverse the input string
for (int i = 0; i < n; i++) {
if (S.charAt(i) == '(') {
current_max++;
if (current_max > max) {
max = current_max;
}
} else if (S.charAt(i) == ')') {
if (current_max > 0) {
current_max--;
} else {
return -1;
}
}
}
if (current_max != 0) {
return -1;
}
return max;
}
public static void main(String[] args) {
String s = "( ((X)) (((Y))) )";
System.out.println(maxDepth(s));
}
}
# A Python program to find the maximum depth of nested
# parenthesis in a given expression
def maxDepth(S):
current_max = 0
max = 0
n = len(S)
for i in range(n):
if S[i] == '(':
current_max += 1
if current_max > max:
max = current_max
elif S[i] == ')':
if current_max > 0:
current_max -= 1
else:
return -1
if current_max != 0:
return -1
return max
s = "( ((X)) (((Y))) )"
print (maxDepth(s))
@gsrai
Copy link
Author

gsrai commented May 20, 2022

var maxDepth = function(s) {
    let cur = 0
    let max = 0
    
    for (let i = 0; i < s.length; i++) {
        if (s[i] === '(') {
            cur++
            if (cur > max) {
                max = cur
            }
        }
        
        if (s[i] === ')') {
            cur--
        }
    }
    return max
};

vs go impl

func maxDepth(s string) int {
	max := 0
	cur := 0
	for _, char := range s {
		if char == '(' {
			cur++
			if cur > max {
				max = cur
			}
		}
		if char == ')' {
			cur--
		}
	}
	return max
}
Runtime Memory Language
96 ms 42.3 MB javascript
2 ms 1.9 MB golang

javascript
golang

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment