Maximum Nesting Depth of the Parentheses

[Question]: In a given string find maximum depth of parentheses. input string has only “( )” type parentheses
Example: Input = “(1+(5*8)+((9)/2))+100” || Output = 2

// TC: O(N)
// SC: O(1)
func maxDepth(_ s: String) -> Int {
    var res = 0;
    var cur = 0
    
    for c in s {
        if c == "(" {
            cur += 1
            res = max(res, cur)
        }
        if c == ")" {
            cur -= 1
        }
    }
    return res
}
let ipParanth = "(1+(5*8)+((9)/2))+100"
let opMaxDepth = maxDepth(ipParanth)
print("max depth--", opMaxDepth)// 3

Leave a Comment

Your email address will not be published. Required fields are marked *