Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the length of the longest arithmetic subsequence.
Problem: Find the length of the longest arithmetic subsequence.
def longest_ap(a):
dp = [{} for _ in a]; best = 1
for i in range(len(a)):
for j in range(i):
d = a[i] - a[j]
dp[i][d] = dp[j].get(d, 1) + 1
best = max(best, dp[i][d])
return best
print(longest_ap([9, 4, 7, 2, 10]), longest_ap([20, 1, 15, 3, 10, 5, 8]))What is printed?- A. 2 4
- B. 3 4
- C. 3 3
- D. 3 5
Correct answer: B. 3 4
dp[i][d] = length of the longest arithmetic subsequence ending at i with difference d. [9, 4, 7, 2, 10] → 4, 7, 10 (d = 3). [20, 1, 15, 3, 10, 5, 8] → 20, 15, 10, 5 (d = −5). O(n²) time and space.
More Coding Interview Problems questions
- Problem: Length of the longest strictly increasing subsequence with the O(n²) DP. cpp int lis(vector<int>& a) { vector<int> dp(a.size()…
- Problem: A hash table keyed by short strings uses Java's String.hashCode. Why do some keys collide? java // String.hashCode: h = 31h + c…
- Problem: Binary search on large indices in C++ (int is 32-bit). cpp int lo = 2000000000, hi = 2100000000; int bad = (lo + hi) / 2; //…
- Problem: Find the celebrity (known by all, knows nobody) with O(n) calls to knows(a, b). python M = [[0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 0…
- Problem: Delete exactly one element from a binary array and return the longest run of 1s that can remain. python def afterdelete(a): l =…
- Problem: Find the minimum number of railway platforms with a sweep line over arrival and departure events (a train arriving when another…