Longest Arithmetic Subsequence of Given Difference (LeetCode 1218): Solution and Explanation

Medium
Array
Hash Table
Dynamic Programming

Given an array and a fixed step called difference, find the longest subsequence where each element equals the previous one plus difference. Return its length; a single element always counts as length 1.

Intuition

The general longest arithmetic subsequence problem needs a DP over pairs because the step is unknown. Here the step is given, which removes a whole dimension.

If x ends a valid subsequence, the element right before it is forced: it has to be x - difference. There is no choice to make about which predecessor to use, only whether one exists.

So it is enough to remember, for each value, the longest chain seen so far that ends on that value. When x arrives, look up x - difference and add one.

Scanning from left to right keeps the order correct: anything already in the map came from an earlier index.

Approach: One-pass hash map DP

  1. Create an empty map dp from value to chain length and set best = 0.
  2. For each x in arr, in order, compute dp[x] = dp.get(x - difference, 0) + 1.
  3. Update best = max(best, dp[x]).
  4. Return best.

Step-by-step example

arr = [1,5,7,8,5,3,4,2,1], difference = -2
  1. x = 1 looks up 3, missing, so dp[1] = 1. x = 5 looks up 7, missing, so dp[5] = 1. x = 7 looks up 9, missing, so dp[7] = 1. x = 8 gives dp[8] = 1.
  2. x = 5 (second time) looks up 7 and finds 1, so dp[5] = 2: the chain 7, 5.
  3. x = 3 looks up 5 and finds 2, so dp[3] = 3: 7, 5, 3. Then x = 4 looks up 6, missing, so dp[4] = 1, and x = 2 finds dp[4] = 1, so dp[2] = 2.
  4. x = 1 looks up 3 and finds 3, so dp[1] = 4: 7, 5, 3, 1. That is the answer, 4.

Code: Python, Java, C++

1class Solution:
2    def longestSubsequence(self, arr: List[int], difference: int) -> int:
3        dp = {}
4        best = 0
5        for x in arr:
6            dp[x] = dp.get(x - difference, 0) + 1
7            best = max(best, dp[x])
8        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each element does one hash map lookup and one write, both O(1) on average.

Space

O(n)

The map holds at most one entry per distinct value.

Other approaches

Pairwise DP (time O(n^2), space O(n))

For each j, check every i < j with arr[j] - arr[i] = difference and take dp[i] + 1. It is correct but O(n^2), which is too slow for 10^5 elements.

Array instead of a map (time O(n), space O(range))

Values lie in [-10^4, 10^4], so an array of size 20001 offset by 10^4 can replace the hash map. Lookups of x - difference outside the range simply count as 0.

Common mistakes

  • Looking up x + difference instead of x - difference. The map stores chains that end on a value, so the predecessor is x - difference.
  • Returning 0 for a non-empty array. Any single element is a valid subsequence of length 1.
  • Worrying about duplicates. When a value repeats, the later write is at least as large as the earlier one, so overwriting dp[x] never loses a better chain.
  • Using a pairwise O(n^2) DP. It times out on the largest inputs.

Frequently asked questions

What happens when difference is 0?

Then x - difference is x itself, so dp[x] counts how many times x has appeared so far. The answer is the frequency of the most common value.

Why is overwriting dp[x] safe for repeated values?

The second occurrence of x can extend every chain the first one could, plus any chains that reached x - difference in between. Its length is never smaller.

How is this different from Longest Arithmetic Subsequence (LeetCode 1027)?

There the step is unknown, so the DP has to remember the step for every pair, which costs O(n^2). Here the step is fixed, so a single map keyed by value is enough.