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: [9,4,7,2,10]947210012344710+3+3Arithmetic subsequence: [4, 7, 10]Common difference: 3Length: 3
Understanding the Visualization
1
Input Array
Given array with various numbers
2
Find Differences
Calculate differences between all pairs
3
Build Sequences
Extend arithmetic sequences with same difference
Key Takeaway
🎯 Key Insight: Use dynamic programming to track the longest arithmetic sequence ending at each position for every possible common difference
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