Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Problem: Reconstruct an actual longest strictly increasing subsequence with the O(n²) DP and parent pointers (the first maximal end index wins).

Problem: Reconstruct an actual longest strictly increasing subsequence with the O(n²) DP and parent pointers (the first maximal end index wins).
def lis(a):
    n = len(a); dp = [1] * n; par = [-1] * n
    for i in range(n):
        for j in range(i):
            if a[j] < a[i] and dp[j] + 1 > dp[i]: dp[i], par[i] = dp[j] + 1, j
    i = dp.index(max(dp)); out = []
    while i != -1: out.append(a[i]); i = par[i]
    return out[::-1]
print(lis([5, 2, 8, 6, 3, 6, 9, 7]))
What is printed?
  1. A. [2, 3, 6, 7, 9]
  2. B. [5, 8, 9]
  3. C. [2, 3, 6, 9]
  4. D. [2, 6, 7]

Correct answer: C. [2, 3, 6, 9]

dp values: 5→1, 2→1, 8→2, 6→2, 3→2, 6→3, 9→4, 7→4. The first index with dp = 4 is the 9; following parents: 9 ← 6 (index 5) ← 3 ← 2. So [2, 3, 6, 9]; [2, 3, 6, 7] has the same length but ends later. The trap option has length 5, which is impossible here.

More Coding Interview Problems questions

Exams that ask this topic