Reputation: 39
Starting to leetcode and get Time Exceed Limit error.
Here is the function:
def containsDuplicate(nums: list[int]) -> bool:
tempset = []
for n in nums:
if n in tempset:
return True
else:
tempset.append(n)
return False
When I just use an array(list), it gives the error. If tempset is a set(), it does not.
What is the difference between time complexities of the two operations? Shouldnt they both run in constant time? Or the problem is with n in tempset
and how it calculates it behind the scene?
Upvotes: 0
Views: 68
Reputation: 23
The issue here is with the line- if n in tempset:
When tempset is a list, the above line of code takes O(n) to execute as it iterates over each index to perform the check.
When tempset is a set, the above line of code takes O(1) to execute. Sets are implemented as hash tables, and they use a hash function to quickly locate the element in the set, making membership tests very efficient.
Upvotes: 0