Search code examples
javascriptnestedparentheses

JS - How to find the index of deepest pair of parentheses?


I have a string: "5 * ((6 + 2) - 1)" I need to find the deepest pair of parentheses and their contents.

I've googled a lot and I can't find anything specific to finding the index. A lot of solutions found how many levels there are, and things like that, but nothing was really helpful. I was thinking of counting the layers, and then using a loop to solve and repeat solving until done, but it seems like this would be really slow.

I have no idea where to start, so I haven't written any code yet.

I want a function to return 5, the string index of the deepest set of parentheses. I also need to do the same for the deepest ")", since I need the pair. Example:

const deepestPair = (str) => {
    // Find deepest pair of parentheses
}
deepestPair("(2(5)4)(3)") // Returns [2, 4], the indexes of the deepest open/close parentheses

Solution

  • You could check opening and closing parentheses and use a counter for getting the most nested indices.

    const deepestPair = str => {
        var indices,
            max = 0,
            count = 0,
            last;
        
        [...str].forEach((c, i) => {
            if (c === '(') {
                last = i;
                count++;
                return;
            }
            if (c === ')') {
                if (count > max) {
                    indices = [last, i];
                    max = count;
                }
                count--;
            }
        });    
        return indices;
    }
    
    console.log(deepestPair("(2(5)4)(3)")); // [2, 4]