4

What is the time complexity of calling Python's built-in len() function on collections.deque? I expect it to be O(1), but I haven't found any confirmation of this fact.

navigatore
  • 111
  • 1
  • 6
  • 1
    At least in CPython, see [the defintion of `deque_len`](https://github.com/python/cpython/blob/master/Modules/_collectionsmodule.c#L1023), in which `Py_SIZE(deque)` is just a [macro around a field reference](https://github.com/python/cpython/blob/9bdd2de84c1af55fbc006d3f892313623bd0195c/Include/object.h#L128). I find it unlikely that another implementation would make it slower. – chepner Apr 04 '19 at 12:46
  • the answer is O(1): https://stackoverflow.com/a/1115382/10397775 – marke Apr 04 '19 at 14:00

1 Answers1

7

In CPython time complexity is O(1) indeed. This fact can be deduced by looking at the source code of CPython (look at chepner's comment).

navigatore
  • 111
  • 1
  • 6