Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Given n ≤ 10⁵ integers (not sorted), find the length of the longest run of consecutive values, e.g. [100, 4, 200, 1, 3, 2] → 4 (1, 2, 3, 4). What is the time complexity of the optimal approach?

  1. A. O(n log n) – sorting is unavoidable
  2. B. O(n) – put all values in a hash set and start counting only from values x where x − 1 is absent
  3. C. O(n²) – each value must be extended in both directions
  4. D. O(n √n) – using square-root decomposition

Correct answer: B. O(n) – put all values in a hash set and start counting only from values x where x − 1 is absent

With a hash set, a run is extended only from its smallest element (x − 1 not present), so every value is visited a constant number of times overall: O(n) average. Sorting gives O(n log n), which passes but is not optimal; extending from every element without the start check is O(n²) in the worst case.

More Coding Interview Problems questions

Exams that ask this topic