I think in Line No 44 of your code the reference to a[j] crosses the limits of the string of a. Also your algorithm is not O(len(a) + len(b)). It is (len(a) * len(b)) if all the characters are same in both the strings. Then anyway it will suffer from TLE. I think the problem can be solved using KMP.