Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Longest arithmetic subsequence (not necessarily contiguous) using a dictionary of (difference → length) per index.
Problem: Longest arithmetic subsequence (not necessarily contiguous) using a dictionary of (difference → length) per index.
def las(a):
dp = [dict() for _ in a]; best = 1
for j in range(len(a)):
for i in range(j):
d = a[j] - a[i]
dp[j][d] = dp[i].get(d, 1) + 1
best = max(best, dp[j][d])
return best
print(las([3, 6, 9, 12, 7, 15, 1, 18]))What is printed?- A. 4
- B. 6
- C. 5
- D. 3
Correct answer: B. 6
With difference 3 the subsequence 3, 6, 9, 12, 15, 18 skips 7 and 1, length 6. dp[j][d] extends the best run ending at i with the same difference, giving O(n²) time.
More Coding Interview Problems questions
- Problem: Count all square submatrices made entirely of 1s. python def count(m): R, C = len(m), len(m[0]); tot = 0 dp = [row[:] for row in…
- Problem: Paint n fence posts with k colours so that no three consecutive posts share a colour. python def ways(n, k): same, diff = 0, k…
- Problem: A pointer starts at index 0 of an array of length n; each step it moves left, right or stays (never leaving the array). Count the…
- Problem: Trade a stock any number of times (one share at most), but after selling you must wait one day before buying again. python def…
- Problem: Wildcard matching where '?' matches one character and '' matches any sequence (including empty); the whole string must match…
- Problem: Count the ways to partition a string into substrings that are all palindromes. python def parts(s): n = len(s); dp = [1] + [0] n…