Question presented to candidate: "Given an unsorted list of integers, return the length of the longest run of consecutive values, in O(n) time. Then tell me why you did not just sort it. Use Python."
What a strong answer should cover:
- Build a
set, and only start counting fromxwhenx - 1is not in the set. - Why it is O(n): each number is walked over at most once, about 2n lookups in total (amortized).
- Why not sort: O(n log n) does more work than needed; trade-offs in memory, worst case and constants.
- Python specifics: iterate the
set, not the list, so duplicates are not re-checked;inon a set is average O(1) but on a list is O(n). - Edge cases: empty list, duplicates, negatives.
Clarifying questions expected:
- "Can there be duplicates, and should an empty array return 0?"
- "Is O(n log n) acceptable, or is O(n) required?" — the whole point of the question.
Code / implementation expected: Yes — a short Python function using set.