Longest Arithmetic Subsequence (LeetCode 1027): Solution and Explanation

Medium
Array
Hash Table
Dynamic Programming

Given an array of integers, find the longest subsequence (order kept, elements may be skipped) whose neighbours all differ by the same amount, and return its length.

Intuition

Two numbers are always arithmetic, so the answer is at least 2. The question is how far a run can be extended, and that depends on two things: the element it currently ends on and its step.

If we knew, for each earlier index i and every step d, how long the best run ending at i with step d is, then pairing i with a later j whose difference is exactly d extends that run by one.

So for every pair i < j compute d = nums[j] - nums[i]. The run ending at j with step d is one longer than the run ending at i with step d, or 2 if no such run exists yet.

Each index needs its own table from step to length. A hash map works for any values; since values here are in [0, 500], steps fit in [-500, 500] and a fixed array of 1001 slots is faster.

Approach: DP over (end index, step)

  1. Create one empty map dp[j] per index and set best = 2.
  2. For j from 0 to n - 1, and for each i < j, compute the step d = nums[j] - nums[i].
  3. Set dp[j][d] = dp[i].get(d, 1) + 1: extend the run that ends at i with step d, or start a new run of 2.
  4. Update best with dp[j][d].
  5. Return best.

Step-by-step example

nums = [3, 6, 9, 12]
  1. j = 1: pair (3, 6) has step 3, dp[0] has no step 3, so dp[1][3] = 2.
  2. j = 2: pair (3, 9) gives dp[2][6] = 2. Pair (6, 9) has step 3 and dp[1][3] = 2, so dp[2][3] = 3 and best = 3.
  3. j = 3: pairs (3, 12) and (6, 12) give dp[3][9] = 2 and dp[3][6] = 2. Pair (9, 12) has step 3 and dp[2][3] = 3, so dp[3][3] = 4.
  4. best = 4: the whole array 3, 6, 9, 12 is arithmetic.

Code: Python, Java, C++

1class Solution:
2    def longestArithSeqLength(self, nums: List[int]) -> int:
3        n = len(nums)
4        dp = [{} for _ in range(n)]
5        best = 2
6        for j in range(n):
7            for i in range(j):
8                d = nums[j] - nums[i]
9                dp[j][d] = dp[i].get(d, 1) + 1
10                best = max(best, dp[j][d])
11        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

Every pair i < j is processed once with O(1) map or array work.

Space

O(n^2)

Each index can store up to n different steps in its map (or 1001 slots with the array version, which is O(n * range)).

Other approaches

Fix the first two elements and scan (time O(n^3), space O(n))

For every pair (i, j), count how many later elements continue the run with step nums[j] - nums[i], using a value-to-indices lookup. It is simple but O(n^3) in the worst case.

DP per step value (time O(range * n), space O(range))

Loop over every possible step d from -500 to 500 and, for that step, run a longest-chain DP with a value-indexed array: len[v] = len[v - d] + 1. This is O(range * n) and can be faster when n is large and the value range is small.

Common mistakes

  • Defaulting a missing dp[i][d] to 0 instead of 1. The element at i alone is a run of length 1, so the pair makes 2.
  • Using a single map per step across all indices. The run must end at i specifically, or you lose the order constraint.
  • Forgetting negative steps. Decreasing runs like 20, 15, 10, 5 have d = -5, so array versions need an offset of 500.
  • Starting best at 1. The array always has at least two elements, and any two form an arithmetic run.

Frequently asked questions

Why can a later i safely overwrite dp[j][d]?

If two earlier indices give the same step to j, they have the same value. The later one can extend any run that the earlier one ends, so its stored length is at least as large.

Is a constant sequence like 5, 5, 5 arithmetic?

Yes. Its step is 0, which is allowed, so equal values form runs with d = 0.

How is this different from Longest Increasing Subsequence?

Both pair every j with every earlier i. LIS only needs the length ending at i, while here the run also has to keep the same step, so each index needs one value per step.