I have two functions to remove duplicates from a list:
def solution1(a: List):
seen = set()
result = []
for item in a:
if item not in seen:
seen.add(item)
result.append(item)
return result
def solution2(a: List):
result = []
for item in a:
if item not in result:
result.append(item)
return result
I got solution1
from this SO question. It's time and space complexities are O(n)
.
I believe solution2
also has a space complexity of O(n)
. What is the time complexity? The for
loop is O(n)
but I'm not sure about the in
statement because the length of result
isn't as big as the input a
. Is it also just O(n)
?
Lastly, if both solutions have the same time and space complexities, is either considered "better"? Which should I use in an interview?
It looks like solution1
uses more space (maybe O(2n)
but I know we're supposed to leave off the constant in front) and completes in shorter time (testing for set membership is faster than testing for list membership).