Longest Arithmetic Subsequence
Longest Arithmetic Subsequence is LeetCode 1027 (Medium). Given an integer array nums, return the length of its longest arithmetic subsequence.
- A subsequence keeps some of the elements in their original order. They do not have to be next to each other.
- It is arithmetic when every two neighbours in it differ by the same amount, called the step or common difference. The step can be negative or zero.
nums has up to 1,500 values between 0 and 500. Checking every pair, about a million of them, is affordable; checking every subsequence is not.
- 2 <= nums.length <= 1500
- 0 <= nums[i] <= 500
Intuition
A run is fixed by two things: the index where it ends and its step. Its length alone is not enough. A run ending at the value 9 with step +3 can take a 12 next, but a run ending at 9 with step +5 cannot.
So keep a map for every index: dp[i][d] is the length of the longest run that ends at index i with step d.
Any earlier index j gives the step d = nums[i] − nums[j]. If a run with step d already ends at j, then nums[i] makes it one longer. Otherwise nums[j] and nums[i] start a new run of 2. Trying every pair j < i fills every map.
When whether the next element fits depends on a choice made earlier in the sequence (here, the step), that choice belongs in the DP state. Longest Increasing Subsequence only needs the last value; this problem needs the last value and the step, so each index stores a map instead of one number.
Approach
Before reading on, decide what you must know about a run that ends at index j to tell whether nums[i] can extend it. Is its length enough? Aim for O(n²) time.
Give each index a map
Create dp, a list of n empty hash maps. dp[i][d] will hold the length of the longest run that ends at index i with step d. A map fits because index i only meets the steps that its earlier pairs produce, at most i of them.
Try every earlier partner
For each i from 1 and each j < i, compute diff = nums[i] - nums[j]. Every run of length 2 or more that ends at i has some second-to-last element j, so looping over all j meets every such run.
Extend the run at j, or start a pair
Set dp[i][diff] = dp[j].get(diff, 1) + 1. If a run with this step ends at j, nums[i] makes it one longer. If not, the default 1 stands for nums[j] on its own, and adding nums[i] gives a pair of length 2.
Keep a running best
After each update, set best = max(best, dp[i][diff]). Start best at 2, because the array has at least two elements and any two of them, in order, form an arithmetic run.
Why overwriting dp[i][diff] is safe
Two partners j1 < j2 give the same step only when nums[j1] == nums[j2]. A run ending at j1 could end at j2 instead, since j2 comes later and holds the same value, so the later partner is never worse. The loop reaches j2 last, so the last write is the right one.
Code in Python, C++ and Java
Common pitfalls
Defaulting the lookup to 0
dp[i][diff] = dp[j].get(diff, 0) + 1
dp[i][diff] = dp[j].get(diff, 1) + 1
The default stands for nums[j] on its own, which is one element, not zero. With 0, every new pair counts as 1 and every run comes out one short: [3, 6, 9, 12] returns 3 instead of 4.
Reading the answer from the last map
return max(dp[n - 1].values())
best = max(best, dp[i][diff]) # inside the loop return best
The longest run can end before the last index. For [1, 2, 3, 10] the run 1, 2, 3 ends at index 2, while the map for 10 only holds pairs, so this returns 2 instead of 3.
Indexing an array by a negative step
dp = [[0] * 501 for _ in range(n)] ... dp[i][diff]
dp = [[0] * 1001 for _ in range(n)] ... dp[i][diff + 500]
Steps run from −500 to 500. With the array version, [20, 15, 10] (step −5) reads index −5: out of bounds in C++ and Java, and in Python a silent read from the end of the row that can mix two different steps together.
Edge cases
In [7, 7, 7] every step is 0, and a zero step still counts as arithmetic, so the answer is the full length 3.
The loops run once, the single pair gets length 2, and best already starts at 2, so the answer is 2.
Complexity
i stores at most i steps, and never more than 1,001 because steps run from −500 to 500.Longest Arithmetic Subsequence FAQ
Why use a hash map instead of an array with 1,001 columns?
Both work. Steps lie between −500 and 500, so an n × 1001 array indexed by diff + 500 is valid and usually faster, because nothing is hashed. The map version needs no offset and only stores steps that actually occur.
How is this different from Longest Arithmetic Subsequence of Given Difference?
In that problem (LeetCode 1218) the step is given, so one map from value to run length is enough and the solution runs in O(n). Here the step is unknown, so every pair has to be tried, which costs O(n²).
Is this the same as the longest arithmetic progression problem?
Close. The classic longest arithmetic progression problem gives a sorted array of distinct values, which also allows a two-pointer O(n²) table. Here the array is unsorted and may repeat values, so the map per index is the usual method.