Nesting codility 100% correct solution javascript

Nesting – Codility 100% Correct Javascript Solution

The Nesting – Codility Challenge is a variant of the Brackets algorithm I solved a few days ago.

The difference here is that we have fewer types of brackets and at the same time we can have several properly nested groups that don’t contain each other. For example (()(()))()(()()) is an acceptable form of a properly nested string.

As before we use a stack to keep track of what’s properly nested and what not. At each step we test if the element we are placing is a closing bracket, and if yes, it must close the previous open bracket in the stack. If the closing happened, we eliminate the opening bracket from the stack.
If at the end the stack is empty we return 1 (the string is properly nested). Otherwise we return 0.

Solution in Javascript with O(N) complexity

function solution(S) {
    // write your code in JavaScript (Node.js 8.9.4)
    let progress = true
    let index = 0
    let stack = []
    let error = false
    while (index < S.length) {
        if (stack.length === 0) {
            if (S[index] === ')' ) {
                 return 0
            } else {
            stack.push(S[index])
            }
        }
        else if (is_properly_nested(stack[stack.length-1],S[index])) {
            stack.pop(stack[stack.length-1])
        } else {
            if (S[index] === ')' ) {
                return 0
            }
            else {
                stack.push(S[index])
            }
        }
        index ++
    }

    if (stack.length === 0) {
        return 1
    } else {
        return 0
    }
}

function is_properly_nested(a,b){
    if  (a === '(' && b === ')')  {
        return true
    }
    else {
        return false
    }
}

And here is the report.

Leave a Reply