Data Structures & AlgorithmsVery hardProduct company OA
Patience-sorting tails array for the longest STRICTLY increasing subsequence, and the length for the non-decreasing variant. What is printed?
Patience-sorting tails array for the longest STRICTLY increasing subsequence, and the length for the non-decreasing variant. What is printed?
import bisect
def tails(a, strict=True):
t = []
for x in a:
i = (bisect.bisect_left if strict else bisect.bisect_right)(t, x)
if i == len(t): t.append(x)
else: t[i] = x
return t
a = [3, 5, 5, 2, 8, 4, 6, 6, 9, 1]
print(tails(a), len(tails(a, False)))- A. [1, 4, 6, 9] 4
- B. [1, 4, 6, 9] 6
- C. [3, 4, 6, 9] 6
- D. [2, 4, 6, 9] 7
Correct answer: B. [1, 4, 6, 9] 6
tails[k] is the smallest possible last value of an increasing subsequence of length k + 1; it is not itself a subsequence (here 1 arrives last and overwrites tails[0]). Its length is the LIS length, 4 (e.g. 3, 5, 8, 9). For non-decreasing subsequences, bisect_right lets equal values extend: 3, 5, 5, 6, 6, 9 → 6. Mixing up bisect_left and bisect_right is exactly the strict / non-strict bug. O(n log n).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Weighted interval scheduling (start, end, value): DP over jobs sorted by end time with binary search for the last compatible job, versus…
- Broken-profile DP: number of ways to tile a 3 × n board with 1 × 2 dominoes, column by column with a 3-bit mask of cells already covered…
- Digit DP (position, running sum, tight flag) counts integers in [0, N] whose digits sum to 10, cross-checked by brute force. What is…
- All suffixes of 'banana' are inserted into a character trie (a suffix trie). What is printed (trie nodes including the root, distinct…
- BFS 2-colouring of each component of an undirected graph. What is printed (components, bipartite components)? python from collections…
- Binary lifting for lowest common ancestors (up[k][v] is the 2ᵏ-th ancestor; the root is its own parent). What is printed? python LOG = 4…