Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Longest increasing subsequence in O(n log n) with a 'tails' array (tails[i] = smallest possible tail of an increasing subsequence of length i + 1).

Problem: Longest increasing subsequence in O(n log n) with a 'tails' array (tails[i] = smallest possible tail of an increasing subsequence of length i + 1).
from bisect import bisect_left
def tails_of(a):
    t = []
    for x in a:
        i = bisect_left(t, x)
        if i == len(t): t.append(x)
        else: t[i] = x
    return t
print(tails_of([3, 10, 2, 1, 20, 4, 6, 7]))
What is printed?
  1. A. [1, 4, 6, 7]
  2. B. [3, 4, 6, 7]
  3. C. [1, 10, 20]
  4. D. [2, 4, 6, 7]

Correct answer: A. [1, 4, 6, 7]

Trace: [3] → [3,10] → [2,10] → [1,10] → [1,10,20] → [1,4,20] → [1,4,6] → [1,4,6,7]. Each value replaces the first tail ≥ it, so only the length (4) is guaranteed meaningful; the array is not in general a real subsequence.

More Coding Interview Problems questions

Exams that ask this topic