What could be the more efficient way of solving the 'sequence land' problem?

I have been trying to solve the problem SEQUENCE LAND and I have got ac but the complexity of My Solution is O(N^2).
I would like to know what would be the more efficient way of solving this problem. Constraints in this problem were fairly small, my solution would have not worked otherwise.

Take help of the queue to enhance the quality of code,,
soln is  analogous to bfs algo
*where prez is the root ......*

you may consider this.