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?- A. Q and R are both correct and O(n), because sets and dicts both preserve insertion order since Python 3.7
- B. P is O(n) because `in` on a list is a hash lookup once the list has been built with append
- C. S is the fastest correct version because a comprehension avoids the per-element cost of slicing and membership tests
- 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
- What is printed? python class Base: registry = [] def initsubclass(cls, kw): cls.registry.append(cls.name) cls.tag = kw.get("tag"…
- What is printed? python class CM: def init(self, name, swallow): self.name, self.swallow = name, swallow def enter(self): print("in" +…
- What is printed? python import bisect a = [1, 3, 3, 3, 7] i, j = bisect.bisectleft(a, 3), bisect.bisectright(a, 3) bisect.insortleft(a…
- What is printed? python from itertools import groupby s = "aabbbaac" g1 = [(k, len(list(v))) for k, v in groupby(s)] g2 = {k: len(list(v))…
- What is printed? python print("abc" 2 + "d", len("abc" 0))
- What is printed? python x = [10, 20, 30, 40, 50] print(x[-1], x[len(x) // 2], x[-2:])