Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the time complexity to check if a dictionary has a key? [duplicate]

According to https://wiki.python.org/moin/TimeComplexity given a dictionary D the operation D[k] is constant.
What is the complexity of k in D ? Is this still constant?

like image 550
Donbeo Avatar asked Mar 18 '23 20:03

Donbeo


1 Answers

Membership testing has the exact same cost as retrieving an item, so O(1).

That's only logical, because in order to return the value of a given key, you first need to determine if it is in the dictionary. If retrieving a key takes constant time, then determining if it is in the dictionary in the first place can only ever take constant time, too.

like image 104
Martijn Pieters Avatar answered Apr 07 '23 06:04

Martijn Pieters