ProgrammingVery hardProduct company OA

A log pipeline must remove duplicate event ids from a list xs of n = 2·10⁵ integers while keeping the order of first occurrence. Four candidates:

A log pipeline must remove duplicate event ids from a list `xs` of n = 2·10⁵ integers while keeping the order of first occurrence. Four candidates:
# P
out = []
for x in xs:
    if x not in out: out.append(x)
# Q
out = list(dict.fromkeys(xs))
# R
out = list(set(xs))
# S
out = [x for i, x in enumerate(xs) if x not in xs[:i]]
Which statement is correct?
  1. A. Q and R are both correct and O(n), because sets and dicts both preserve insertion order since Python 3.7
  2. B. P is O(n) because `in` on a list is a hash lookup once the list has been built with append
  3. C. S is the fastest correct version because a comprehension avoids the per-element cost of slicing and membership tests
  4. D. Only Q is both correct and O(n); P and S are correct but O(n²), and R is O(n) but does not guarantee the order

Correct answer: D. Only Q is both correct and O(n); P and S are correct but O(n²), and R is O(n) but does not guarantee the order

`x in list` is a linear scan, so P does up to 1 + 2 + … + n ≈ 2·10¹⁰ comparisons when most ids are distinct – a certain TLE. S is worse: it also copies a prefix on every step. dict preserves insertion order (a language guarantee since 3.7) and fromkeys is one hash insert per element, so Q is O(n) expected. A set has NO order guarantee – only dicts do – so R can return the ids in any order.

More Python Programming questions

Exams that ask this topic