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?
  1. A. 2 4
  2. B. 3 4
  3. C. 3 3
  4. 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

Exams that ask this topic