Data Structures & AlgorithmsHardTCS Digital · Infosys SP

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 = [14, 9, 16, 18, 12, 10, 17, 23, 3, 11, 21]
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. 4 11
  2. B. 4 6
  3. C. 5 6
  4. D. 4 5

Correct answer: B. 4 6

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

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

Exams that ask this topic