Data Structures & AlgorithmsVery hardProduct company OA

Problem: Return (length of the longest strictly increasing subsequence, number of such longest subsequences).

Problem: Return (length of the longest strictly increasing subsequence, number of such longest subsequences).
def num_lis(a):
    n = len(a); L = [1] * n; C = [1] * n
    for i in range(n):
        for j in range(i):
            if a[j] < a[i]:
                if L[j] + 1 > L[i]: L[i], C[i] = L[j] + 1, C[j]
                elif L[j] + 1 == L[i]: C[i] += C[j]
    m = max(L)
    return m, sum(c for l, c in zip(L, C) if l == m)
print(num_lis([1, 4, 2, 5, 3, 6]), num_lis([3, 3, 3]))
What is printed?
  1. A. (4, 3) (1, 1)
  2. B. (3, 3) (1, 3)
  3. C. (4, 3) (1, 3)
  4. D. (4, 2) (1, 3)

Correct answer: C. (4, 3) (1, 3)

C[i] counts longest increasing subsequences ending at i: a strictly better length resets it to C[j], an equal length adds C[j]. Length 4 via 1, 4, 5, 6 / 1, 2, 5, 6 / 1, 2, 3, 6 → 3. With equal values every single element is an LIS of length 1 → 3. Summing C over all i (not only those with maximal L) is the usual bug. O(n²).

More Coding Interview Problems questions

Exams that ask this topic