Data Structures & AlgorithmsHardFlipkart/Uber OA · placement

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 = [17, 3, 21, 11, 19, 7, 1, 23, 5, 4, 20]
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 11
  2. B. 5 7
  3. C. 3 7
  4. D. 2 7

Correct answer: C. 3 7

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

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

Exams that ask this topic