-1

I have this method

arr // input


new_ seq = []

for i in arr:
  new_seq.append(i)
  __new_seq = [x for i, x in enumerate(arr) if x not in new_seq]
  for j in __new_seq:
      new_seq.append(j)
      __new_seq = [x for i, x in enumerate(arr) if x not in new_seq]
      for k in __new_seq:
          new_seq.append(k)

How to calculate the time complexity for this method Please note that each loop has a smaller length than the one before

1 Answers1

2

Ordinarily, a loop that executes only part of the time counts as a normal loop - complexity analysis ignores constant factors. That would make it cubic time complexity.

In this case, though, the inner loops never execute, so it should be quadratic time (the middle loop body never executes, but you still spend time iterating the second for...in).

Kilian Foth
  • 107,706
  • 45
  • 295
  • 310
  • 1
    Please see the updated code. The first loop takes all the arr elements O(n) The second and the third loop takes all the elements that has not been added to the new_seq this is not O(n)^3 .... I think its less than that – Farah Amawi Jan 24 '19 at 14:12
  • Just to clarify your answer => time complexity for this code is O(n) ? Regardless the time needed for the second the the third loop?!! – Farah Amawi Jan 24 '19 at 14:16
  • @FarahAmawi That's how big O works. Doesn't mater how big or small constant factors are. – candied_orange Jan 25 '19 at 02:05