Pick the fix
Which change keeps this O(n)?
def longest(nums: list[int]) -> int:
s, best = set(nums), 0
for x in s:
y = x
while y + 1 in s:
y += 1
best = max(best, y - x + 1)
return best
print(longest([3, 1, 2]))Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Start counting only when x - 1 not in s
Right: each run is then walked once, from its smallest number.
The guard turns many overlapping walks into exactly one walk per run, so total steps stay proportional to the number of distinct values.
Why not the others?
- B Sort the set before the loop. That adds O(n log n) and does not stop repeated walks.
- C Use a list instead of a set. Membership checks become O(n) each, making it slower.