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

Exams that ask this topic