ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
import bisect
a = [10, 9, 2, 5, 3, 7, 101, 18]
tails = []
for x in a:
    i = bisect.bisect_left(tails, x)
    if i == len(tails):
        tails.append(x)
    else:
        tails[i] = x
print(len(tails), tails)
  1. A. 4 [2, 3, 7, 18]
  2. B. 4 [2, 3, 7, 101]
  3. C. 3 [2, 3, 7]
  4. D. 5 [2, 3, 7, 18, 101]

Correct answer: A. 4 [2, 3, 7, 18]

This is the O(n log n) longest increasing subsequence. tails[k] holds the smallest possible tail of an increasing run of length k+1. The final tails list has length 4, but its contents are not themselves one valid subsequence.

More Python Programming questions

Exams that ask this topic