AlgoInsight

DSA problem

Longest Arithmetic Subsequence

MediumLongest Increasing Subsequence (LIS)Pattern: Longest Increasing Subsequence (LIS)top600GoogleAmazonMicrosoftBloombergAdobe

Given an array nums of integers, return the length of the longest arithmetic subsequence in nums. A subsequence is derived by deleting zero or more elements without changing the order of the remaining ones. An arithmetic subsequence is one whose consecutive differences are all the same constant d.

Unlike a contiguous arithmetic slice problem, here the elements may be far apart in the original array. The common difference d can be any integer (positive, zero, or negative), so we cannot enumerate d cheaply ahead of time. A pure O(n²) length-DP on indices alone does not work because the recurrence depends on which common difference is being extended.

The trick is to keep, for every index i, a hash map dp[i] keyed by common difference d whose value is the length of the longest arithmetic subsequence ending at index i with that difference. For every pair j < i, compute d = nums[i] - nums[j]. If an arithmetic subsequence ending at j with difference d already exists, extend it: dp[i][d] = dp[j][d] + 1. Otherwise we are starting a new two-element subsequence [nums[j], nums[i]] so dp[i][d] = 2.

The final answer is the maximum value found in any dp[i][d] over the entire computation. The algorithm runs in O(n²) time and O(n²) space in the worst case, which is sufficient for the typical constraint n <= 1000.

Examples

Example 1
Input: nums = [3,6,9,12]
Output: 4
Explanation: The whole array is an arithmetic subsequence with common difference 3, so the answer is 4.
Example 2
Input: nums = [9,4,7,2,10]
Output: 3
Explanation: A longest arithmetic subsequence is [4,7,10] with common difference 3, giving length 3.
Example 3
Input: nums = [20,1,15,3,10,5,8]
Output: 4
Explanation: A longest arithmetic subsequence is [20,15,10,5] with common difference -5, giving length 4.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arrayhash-tabledynamic-programmingbinary-search

Browse all DSA problems