Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the longest bitonic subsequence (strictly increasing then strictly decreasing; either part may be empty) using LIS from the left and from the right.
Problem: Find the longest bitonic subsequence (strictly increasing then strictly decreasing; either part may be empty) using LIS from the left and from the right.
def bitonic(a):
n = len(a); inc = [1] * n; dec = [1] * n
for i in range(n):
for j in range(i):
if a[j] < a[i]: inc[i] = max(inc[i], inc[j] + 1)
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
if a[j] < a[i]: dec[i] = max(dec[i], dec[j] + 1)
return max(inc[i] + dec[i] - 1 for i in range(n))
print(bitonic([2, 9, 3, 7, 5, 8, 4, 1]), bitonic([5, 4, 3, 2]), bitonic([1, 2, 3]))What is printed?- A. 5 4 3
- B. 7 4 3
- C. 6 1 3
- D. 6 4 3
Correct answer: D. 6 4 3
inc[i] is the longest increasing subsequence ending at i, dec[i] the longest decreasing one starting at i; the peak is counted twice, hence − 1. With peak 8: 2, 3, 7, 8 (4) + 8, 4, 1 (3) − 1 = 6. A purely decreasing or increasing array is bitonic by itself. O(n²) (O(n log n) with patience sorting).
More Coding Interview Problems questions
- Problem: Numbers whose only prime factors are 2, 3 and 5 (1 included) are generated in order with three pointers. python def ugly(n): u =…
- Problem: A chess knight hops on a phone keypad (1-9 in a 3 × 3 grid, 0 below 8). Count the distinct numbers of length n it can dial (start…
- Problem: Trade a stock any number of times (hold at most one share); each completed sale pays a fixed fee. Maximise profit with two…
- Problem: Is c formed by interleaving a and b (keeping each string's internal order)? dp[i][j] = first i chars of a and j chars of b can…
- Problem: Wildcard matching over the whole string: '?' matches any one character, '' matches any sequence (including empty). python def…
- Problem: Return (length of the longest strictly increasing subsequence, number of such longest subsequences). python def numlis(a): n =…