Longest Arithmetic Subsequence
Problem
Given an integer array nums, return the length of the longest subsequence in which consecutive elements have the same difference. A subsequence keeps the original order but may skip elements; a sequence a_0, a_1, ..., a_k is arithmetic when a_{i+1} - a_i is the same value for every i. Any subsequence of length 1 or 2 is arithmetic by definition.
numsholds up to about a thousand integers.- Each value is a non-negative integer no larger than a few hundred.
Examples
nums = [2, 6, 10, 14]→4. The whole array has difference 4.nums = [8, 3, 6, 1, 9]→3.3, 6, 9has difference 3.nums = [16, 1, 12, 3, 8, 5, 7]→4.1, 3, 5, 7has difference 2.
Hints
- An arithmetic subsequence is determined by where it ends and what its difference is. Fix both and ask how it could have been built.
- For a subsequence ending at index
iwith differenced, the element before the last must be at somej < iwithnums[j] = nums[i] - d. - DP with state
(index, difference):length[i][d] = length[j][d] + 1for eachj < i,d = nums[i] - nums[j], stored in a dictionary or a dense table over the difference range.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.