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.
And here is the report.