Longest Arithmetic Subsequence - Problem

Given an array nums of integers, return the length of the longest arithmetic subsequence in nums.

Note that:

  • A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
  • A sequence seq is arithmetic if seq[i + 1] - seq[i] are all the same value (for 0 <= i < seq.length - 1).

Input & Output

Example 1 — Basic Arithmetic Sequence
$ Input: nums = [3,6,9,12]
Output: 4
💡 Note: The entire array forms an arithmetic subsequence with common difference 3: [3,6,9,12]. Length = 4.
Example 2 — Multiple Arithmetic Subsequences
$ Input: nums = [9,4,7,2,10]
Output: 3
💡 Note: The longest arithmetic subsequences are [4,7,10] with difference 3, and [9,7,2] with difference -3. Both have length 3.
Example 3 — No Long Arithmetic Sequence
$ Input: nums = [20,1,15,3,10,5,8]
Output: 4
💡 Note: The longest arithmetic subsequence is [20,15,10,5] with common difference -5. Length = 4.

Constraints

  • 2 ≤ nums.length ≤ 1000
  • 0 ≤ nums[i] ≤ 500

Visualization

Tap to expand
Longest Arithmetic Subsequence Space-Optimized Dynamic Programming Approach INPUT Array nums: 3 i=0 6 i=1 9 i=2 12 i=3 Common Difference: d=3 d=3 d=3 Arithmetic Subsequence: Derived by deleting elements with constant difference seq[i+1] - seq[i] = const nums = [3, 6, 9, 12] Length: 4 elements ALGORITHM STEPS 1 Initialize DP dp[i] = map of diff --> length 2 Iterate Pairs For each i,j where j < i 3 Calculate Difference diff = nums[i] - nums[j] 4 Update DP dp[i][diff] = dp[j][diff] + 1 DP State (diff=3): idx 0 1 2 3 len 1 2 3 4 Complexity: Time: O(n^2) | Space: O(n*d) d = number of unique differences FINAL RESULT Longest Arithmetic Subsequence: 3 6 9 12 All 4 elements form AP! OUTPUT 4 Verification: 6 - 3 = 3 [OK] 9 - 6 = 3 [OK] 12 - 9 = 3 [OK] Constant diff = 3 Key Insight: Space-optimized DP uses a hashmap at each index to track subsequence lengths for different differences. For each pair (i,j), we extend the sequence ending at j with difference d by checking dp[j][d] and adding 1. The maximum value across all dp[i][d] entries gives us the longest arithmetic subsequence length. TutorialsPoint - Longest Arithmetic Subsequence | Space-Optimized DP Approach
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
89.3K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen