Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of dict.keys() in Python?

Tags:

python

I came across a question when I solved this LeetCode problem. Although my solution got accepted by the system, I still do not have any idea after searching online for the following question:

What is the time complexity of dict.keys() operation?

Does it return a view of the keys or a real list (stores in memory) of the keys?

like image 904
Jason Avatar asked Aug 30 '16 05:08

Jason


People also ask

What is the time complexity of dict in Python?

If we explain the difference by Big O concepts, dictionaries have constant time complexity, O(1) while lists have linear time complexity, O(n).

What does dict keys () do in Python?

Python Dictionary keys() The keys() method extracts the keys of the dictionary and returns the list of keys as a view object.

What is the time complexity of checking if a key is in a dictionary in Python?

The in operator for dict has average case time-complexity of O(1).

What is the time complexity of searching a key?

keys() would take O(n) time to find nums[i] in the list of keys thus making the time complexity O(n^2).


1 Answers

In Python 2, it's O(n), and it builds a new list. In Python 3, it's O(1), but it doesn't return a list. To draw a random element from a dict's keys, you'd need to convert it to a list, and that conversion is O(n).

It sounds like you were probably using random.choice(d.keys()) for part 3 of that problem. If so, that was O(n), and you got it wrong. You need to either implement your own hash table or maintain a separate list of elements, without sacrificing average-case O(1) insertions and deletions.

like image 75
user2357112 supports Monica Avatar answered Oct 11 '22 20:10

user2357112 supports Monica