LeetCode #1027 Medium

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.

Constraints
  • 2 <= nums.length <= 1500
  • 0 <= nums[i] <= 500
arrayhash-tablebinary-searchdynamic-programming
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶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 i in range(1, n):
▶7 for j in range(i):
▶8 diff = nums[i] - nums[j]
▶9 dp[i][diff] = dp[j].get(diff, 1) + 1
▶10 best = max(best, dp[i][diff])
▶11 return best
306192123stepbest2runs ending here: step → lengthbest starts at 2: any two numbers form a run
n4
best2any pair is arithmetic
Each index gets its own map from a step (the common difference) to the length of the longest run that ends at that index with that step. All maps start empty. The answer starts at 2 because any two numbers, in order, already form an arithmetic run.
30j61i92123step6−3=+3best2runs ending here: step → length+3 → 2no step +3 run ends at 3 → new run of 2
pairindex 0 → 13 then 6
step+3
run length2new pair
best2
Index 0 has no run with step +3, so the lookup falls back to 1 (the number 3 on its own) and the pair 3, 6 starts a run of 2.
30j6192i123step9−3=+6best2runs ending here: step → length+3 → 2+6 → 2no step +6 run ends at 3 → new run of 2
pairindex 0 → 23 then 9
step+6
run length2new pair
best2
Index 0 has no run with step +6, so the lookup falls back to 1 (the number 3 on its own) and the pair 3, 9 starts a run of 2.
3061j92i123step9−6=+3best3runs ending here: step → length+3 → 2+6 → 2+3 → 36 ends a step +3 run of 2 → 9 makes 3, new best
pairindex 1 → 26 then 9
step+3
run length3extends 2
best3
Index 1 already has a run with step +3 of length 2. Adding 9 keeps the same step, so it becomes a run of 3 ending at index 2. That beats the best so far.
30j6192123istep12−3=+9best3runs ending here: step → length+3 → 2+6 → 2+3 → 3+9 → 2no step +9 run ends at 3 → new run of 2
pairindex 0 → 33 then 12
step+9
run length2new pair
best3
Index 0 has no run with step +9, so the lookup falls back to 1 (the number 3 on its own) and the pair 3, 12 starts a run of 2.
3061j92123istep12−6=+6best3runs ending here: step → length+3 → 2+6 → 2+3 → 3+9 → 2+6 → 2no step +6 run ends at 6 → new run of 2
pairindex 1 → 36 then 12
step+6
run length2new pair
best3
Index 1 has no run with step +6, so the lookup falls back to 1 (the number 6 on its own) and the pair 6, 12 starts a run of 2.
306192j123istep12−9=+3best4runs ending here: step → length+3 → 2+6 → 2+3 → 3+9 → 2+6 → 2+3 → 49 ends a step +3 run of 3 → 12 makes 4, new best
pairindex 2 → 39 then 12
step+3
run length4extends 3
best4
Index 2 already has a run with step +3 of length 3. Adding 12 keeps the same step, so it becomes a run of 4 ending at index 3. That beats the best so far.
306192123stepbest4runs ending here: step → length+3 → 2+6 → 2+3 → 3+9 → 2+6 → 2+3 → 4answer: 4 (3, 6, 9, 12)
answer4
run3, 6, 9, 12step +3
Every pair has been tried, so every run has been counted. The longest is 4, with step +3, ending at index 3. Following each step back to the index that produced it recovers the run itself, highlighted in the array.
05

Common pitfalls

Defaulting the lookup to 0

✗ Wrong
dp[i][diff] = dp[j].get(diff, 0) + 1
✓ Right
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

✗ Wrong
return max(dp[n - 1].values())
✓ Right
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

✗ Wrong
dp = [[0] * 501 for _ in range(n)]
...
dp[i][diff]
✓ Right
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.

06

Edge cases

All values equal

In [7, 7, 7] every step is 0, and a zero step still counts as arithmetic, so the answer is the full length 3.

Only two elements

The loops run once, the single pair gets length 2, and best already starts at 2, so the answer is 2.

07

Complexity

Time
O(n²)
Space
O(n²)
There are n(n − 1)/2 pairs, each with O(1) average map work. Index i stores at most i steps, and never more than 1,001 because steps run from −500 to 500.
08

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.