Answer
Let's assume N
is len(s)
The outer loop has O(N)
complexity because pc
takes all values from 0
to len(s) - 1
. The second loop has the same complexity: although pd
begins from pc + 1
, not from 0
, the two loops together will have the complexity O(N * N / 2) = O(N^2)
. The inner loop will have the O(min(N, P))
complexity (where P
is the p
variable from your function) because the loop will end either when pd + x
reaches len(s)
or when x
reaches p
So, assuming P
is not too small, if I am not mistaken, the overall complexity is O(N^3)
If you are having difficulties understanding why do the inner loops (starting from the outer loop iterable instead of 0
) multiply complexity by N
, not something smaller, please, see this question
Important note
By the way, I guess it would be much easier for you to understand the complexity by yourself if you were using for
loops instead of while
s. I would rewrite the code in the following way (also contains some minor style improvements):
def herhalen(s, p):
for pc in range(len(s)):
for pd in range(pc + 1, len(s)):
if s[pd] == s[pc]:
for x in range(p):
if pd + x < len(s) or s[pc + x] == s[pd + x]:
break
else:
return True
return False
Use all the power of the language you are writing in :)