Data Structures & AlgorithmsHardProduct Company SDE · DP with binary search

Problem: Find the length of the longest strictly increasing subsequence of [10, 9, 2, 5, 3, 7, 101, 18] with the O(n log n) tails method.

Problem: Find the length of the longest strictly increasing subsequence of [10, 9, 2, 5, 3, 7, 101, 18] with the O(n log n) tails method.
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))
What is printed?
  1. A. 4
  2. B. 3
  3. C. 5
  4. D. 6

Correct answer: A. 4

The tails array evolves as [10], [9], [2], [2,5], [2,3], [2,3,7], [2,3,7,101], then [2,3,7,18], so the length is 4. The subsequence 2, 3, 7, 18 realises it.

More Coding Interview Problems questions

Exams that ask this topic