Can anyone help me with LSTBTF

https://www.codechef.com/viewsolution/27872134

I am trying to learn where I did wrong. So, i picked up the C++ solution that was accepted and tried to implement the same in Python 3.6 as I use python. But, for two of the test cases, am getting TLE. Please have a look.

@syntaxhacker, @vijju123 would really appreciate if you could help me.