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?- A. (4, 3) (1, 1)
- B. (3, 3) (1, 3)
- C. (4, 3) (1, 3)
- 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
- Problem: With k identical eggs and an n-floor building, find the minimum number of drops that guarantees finding the critical floor. DP on…
- Problem: Two players alternately take a pile from either END of a row; both play optimally. Compute (first player's total − second…
- Problem: Maximum sum of a non-empty contiguous subarray where you may delete at most one element (the result must stay non-empty). Track…
- Problem: Assign 4 workers to 4 jobs (one each) minimising total cost with a bitmask DP over the set of jobs already taken; compare with…
- Problem: Convert Roman numerals to integers: a symbol smaller than the one after it is subtracted. python def roman(s): v = {"I": 1, "V"…
- Problem: Is b a rotation of a? Check equal lengths and whether b occurs in a + a. python def isrot(a, b): return len(a) == len(b) and b in…