2

The code below is for a challenge that I did recently. I estimate the runtime of this function to be O(n^2) but I am a bit unsure if that is indeed correct, as the if statement line is somewhat expensive and I don't know to what extent should I factor that into my calculation.

Explanation of the If condition from the main code.

Counter-> Dict constructing method of runtime O(n) and operations are O(1)

j not in tupleVal -> O(n) runtime

Main Code

from collections import Counter

def funWith(texts):
   words = set()
   tuples = (0,)
   for i in range(0,len(text)):
       for j in range(i+1,len(text)):
           if Counter(text[i]) == Counter(text[j]) and j not in tuples :
              tuples +=(j,)
              words.add(text[i])
   return (sorted(list(words)) if len(words) > 0 else text)

text = ["cncvbn", "fdhfh", "anagrartyrtyms","cnvcbn"]

print(funWithAnagrams(text))

Any helps appreciated.

Thanks

  • I would think it is `O(n^3)` as the loops take o(n^2) and then that `if ` line can be stated as the following: `O(3n)`->`O(n) `and therefore it would give you `O(n^3)`. Please do correct me if i am wrong anyone. – AzyCrw4282 Nov 05 '20 at 17:19
  • 1
    There are optimizations you can make that won't affect big-O, like only comparing strings if they're the same length. – Barmar Nov 05 '20 at 17:22
  • Instead of creating new Counters every time through the loop, go through the input list once and create a list of Counters. – Barmar Nov 05 '20 at 17:23
  • 1
    @Barmar Thanks. Your 2nd comment is a good way to achieve optimal solution. @@AzyCrw4282 I thought of that solution but I was also dubious. Barmar, can you confirm that if it can be O(n^3)? Thanks. –  Nov 05 '20 at 17:33
  • 1
    Yes. Concatenating tuples is O(n), and you have O(n^2) loop iterations. Why do you need a tuple, use a set for that? – Barmar Nov 05 '20 at 17:35
  • Also `j not in tupleVal` is O(n) as you said. – Barmar Nov 05 '20 at 17:36

1 Answers1

0

Instead of estimating, I would use time.perf_counter. This basically keeps a timer of how long your program takes, and is short for "performance counter". I would first start it up, run through your program, and then capture the time it took. That would be your true runtime. More info is over here: https://www.geeksforgeeks.org/time-perf_counter-function-in-python/

A random coder
  • 453
  • 4
  • 13
  • Doing this to determine big-O complexity requires you to test with many different input sizes and then figure out the relationship. – Barmar Nov 05 '20 at 17:17
  • yes. This seems a plausible way to estimate it but then again it's a tedious task. Are you able to tell the estimate from just by looking at the code? –  Nov 05 '20 at 17:31