What is the Time and Space complexity of this code (Find Uniques and duplicates)?
arr = [1,1,1,2,4,2,5]
a = []
d = []
for i in arr:
if i not in a:
a.append(i)
elif i in a:
d.append(i)
print(a)
print(d)
What is the Time and Space complexity of this code (Find Uniques and duplicates)?
arr = [1,1,1,2,4,2,5]
a = []
d = []
for i in arr:
if i not in a:
a.append(i)
elif i in a:
d.append(i)
print(a)
print(d)
You iterate through arr, which makes complexity O(N). Then you check if i is in a, which adds another N operations. This makes your overall complexity O(N^2).
Memory complexity is O(N), because you take N elements and distribute them between 2 arrays. You don't create any new elements.
Also a small note: consider using else instead of elif i in a, because in this case they mean basically the same thing.