In Python, we can check if an array or list contains duplicate items using the following one-liner function.
def contain_duplicates(list):
return len(set(list)) != len(list)
The idea is to convert the list/array to set, then we can use the len function to get the sizes of the set and the original list/array. If they are both equal, then the array or list does not contain any duplicate items.
>>> contain_duplicates([1,2,3,4])
False
>>> contain_duplicates([1,2,3,4,2])
True
>>> contain_duplicates(["aa", "bb"])
False
>>> contain_duplicates(["aa", "bb", "aa"])
True
Alternatively, you can use the following naive solution based on set.
def contain_duplicates(list):
data = set()
for i in list:
if i in data:
return True
data.add(i)
return False
The time complexity is O(N) and the space requirement is O(N) as well given the size of the list is N.
–EOF (The Ultimate Computing & Technology Blog) —
239 wordsLast Post: Counting the Stepping Numbers between A Range using Depth/Breadth First Search Algorithm
Next Post: The Complex Number Multiplication Function
