Shouldnt the below algorithm be O(n^2) worst case? because we are iterating over the n elements in the array first, then in the worst case the array happens to only contain distinct elements, so when we check in the Set s if an element is present, we have to iterate over n elements again before adding that element, so O(n^2)?
# This function prints all distinct elements
def countDistinct(arr, n):
# Creates an empty hashset
s = set()
# Traverse the input array
res = 0
for i in range(n):
# If not present, then put it in
# hashtable and increment result
if (arr[i] not in s):
s.add(arr[i])
res += 1
return res
# Driver code
arr = [6, 10, 5, 4, 9, 120, 4, 6, 10]
n = len(arr)
print(countDistinct(arr, n))