0

Which time complexety this code have?

line = "..."
occuriences_cnt = {char: line.count(char) for char in line}

I'm assuming that this is 0(n^2), because there is count - O(n) in loop. Am I wrong?

karambaq
  • 631
  • 3
  • 9
  • 24
  • 4
    yes, and you can use `collections.Counter` to reduce it to `O(n)`, see https://stackoverflow.com/questions/42461840/what-is-the-time-complexity-of-collections-counter-in-python – Jean-François Fabre Jul 18 '22 at 18:34
  • Documentation https://docs.python.org/3/library/stdtypes.html#textseq does not say anything about complexity of `.count` so you have to make an educated guess - it is unlikely there is any caching so `count` have to do linear search - O(string_length). I'd recommend writing it out yourself if you need that to explain complexity. – Alexei Levenkov Jul 18 '22 at 18:43
  • This might be helpful https://stackoverflow.com/questions/44812468/what-is-the-time-complexity-of-python-lists-count-function – funnydman Jul 18 '22 at 19:19

0 Answers0