Data Structures & AlgorithmsHardProduct placement · Amazon/Microsoft

Longest run of consecutive integers (in any order) using a hash set and starting only from numbers whose predecessor is absent. What is printed?

Longest run of consecutive integers (in any order) using a hash set and starting only from numbers whose predecessor is absent. What is printed?
a = [7, 1, 14, 11, 3, 20, 15, 22, 10, 2, 16]
s, best, starts = set(a), 0, 0
for x in s:
    if x - 1 not in s:
        starts += 1; y = x
        while y + 1 in s: y += 1
        best = max(best, y - x + 1)
print(best, starts)
  1. A. 3 6
  2. B. 5 6
  3. C. 3 11
  4. D. 3 7

Correct answer: A. 3 6

Only sequence starts (x with x − 1 absent) launch a scan, which keeps the whole pass O(n). Output (longest, number of runs): 3 6.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic