It depends on the elements of s
. If, for instance, all elements of s
are equal, then your condition if s[pd] == s[pc]
will always be true, which will in turn affect the overall complexity. If, however, all elements of s
are distinct, then s[pd] == s[pc]
will only be true when the pd
and pc
hold the same value and therefore pointing to the same element in s
.
Example 1 - Unique elements
s = [i for i in range(20)] #[0,1,2,...,19]
pc = 0
while pc < len(s):
pd = pc + 1
while pd < len(s):
if s[pd] == s[pc]:
print(pd)
pd += 1
pc += 1
In this scenario, the print
function is never executed.
Example 2 - Identical elements
s = [0 for i in range(20)] #[0,0,...,0]
pc = 0
print_counter = 1
while pc < len(s):
pd = pc + 1
while pd < len(s):
if s[pd] == s[pc]:
print(print_counter)
print_counter += 1
pd += 1
pc += 1
In this scenario, the print
function got executed 190 times which is O(n^2).
Note
- Note that for your code, you have an additional loop that you have to consider.
- Also note that there exist more scenarios where the elements of
s
are neither all equal or all unique.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…