Data Structures & AlgorithmsVery hardProduct company OA

Patience-sorting tails array for the longest STRICTLY increasing subsequence, and the length for the non-decreasing variant. What is printed?

Patience-sorting tails array for the longest STRICTLY increasing subsequence, and the length for the non-decreasing variant. What is printed?
import bisect
def tails(a, strict=True):
    t = []
    for x in a:
        i = (bisect.bisect_left if strict else bisect.bisect_right)(t, x)
        if i == len(t): t.append(x)
        else: t[i] = x
    return t
a = [3, 5, 5, 2, 8, 4, 6, 6, 9, 1]
print(tails(a), len(tails(a, False)))
  1. A. [1, 4, 6, 9] 4
  2. B. [1, 4, 6, 9] 6
  3. C. [3, 4, 6, 9] 6
  4. D. [2, 4, 6, 9] 7

Correct answer: B. [1, 4, 6, 9] 6

tails[k] is the smallest possible last value of an increasing subsequence of length k + 1; it is not itself a subsequence (here 1 arrives last and overwrites tails[0]). Its length is the LIS length, 4 (e.g. 3, 5, 8, 9). For non-decreasing subsequences, bisect_right lets equal values extend: 3, 5, 5, 6, 6, 9 → 6. Mixing up bisect_left and bisect_right is exactly the strict / non-strict bug. O(n log n).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic