What does this function return and what are its time/space costs?
def f(nums):
seen = set()
for n in nums:
if n in seen:
return n
seen.add(n)
return -1Options
- Smallest value; O(n log n) time, O(1) space
- First duplicate value; O(n) time, O(n) space (Correct option)
- Count of duplicates; O(n²) time, O(1) space
- Last unique value; O(n) time, O(1) space
Answer
First duplicate value; O(n) time, O(n) space
Why
It walks the list once and remembers each number in a set. The first number already in the set is the first repeated value, so it returns it.
One loop, with O(1) set checks inside: O(n) time. The set can grow to n items: O(n) extra memory.
Without the set you would compare every pair: O(n²).
Remember
A set turns 'have I seen it?' into O(1).