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?- A. [2, 3, 6, 7, 9]
- B. [5, 8, 9]
- C. [2, 3, 6, 9]
- 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
- Problem: Minimum number of single-character insertions plus deletions to turn a into b (no replacements). python def insdel(a, b): m, n =…
- Problem: Fibonacci modulo 10⁹ + 7 by 2 × 2 matrix exponentiation in O(log n). python MOD = 109 + 7 def mul(A, B): return [[(A[0][0]B[0][0]…
- Problem: Count balanced parenthesis strings with n pairs whose nesting depth never exceeds d (DP over position and current depth). python…
- Problem: Count integers in [1, N] whose digits sum to S, with a digit DP over (position, sum so far, tight). python from functools import…
- Problem: Assign 4 workers to 4 jobs (one each) to minimise total cost, with a DP over the bitmask of used jobs. python cost = [[9, 2, 7…
- Problem: Maximum independent set (largest set of pairwise non-adjacent nodes) in a TREE with a two-state DP. python from collections…