Repaso
Español
Algorithms & DSCoreALG-23

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 -1

Options

  1. Smallest value; O(n log n) time, O(1) space
  2. First duplicate value; O(n) time, O(n) space (Correct option)
  3. Count of duplicates; O(n²) time, O(1) space
  4. 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).

Key terms

Practice this question in Repaso