Longest Arithmetic Subsequence - Problem

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

An arithmetic subsequence is a sequence where the difference between consecutive elements is constant. For example, [2, 4, 6, 8] has a common difference of 2.

Important: A subsequence maintains the relative order of elements from the original array, but elements don't need to be contiguous. You can skip elements as needed.

Example: In array [3, 6, 9, 12], the entire array forms an arithmetic subsequence of length 4 with difference 3.

Input & Output

example_1.py โ€” Basic Case
$ Input: [3, 6, 9, 12]
โ€บ Output: 4
๐Ÿ’ก Note: The entire array forms an arithmetic sequence with common difference 3: [3, 6, 9, 12]. Length = 4.
example_2.py โ€” Mixed Sequences
$ Input: [9, 4, 7, 2, 10]
โ€บ Output: 3
๐Ÿ’ก Note: The longest arithmetic subsequence is [4, 7, 10] with common difference 3, or [9, 7, 2] with difference -2. Both have length 3.
example_3.py โ€” No Long Sequence
$ Input: [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
  • -500 โ‰ค nums[i] โ‰ค 500
  • All elements in nums are integers

Visualization

Tap to expand
๐ŸŽต Musical Arithmetic Sequences9Start4Note 17Note 22Note 310EndSequence: 4 โ†’ 7 โ†’ 10Interval: +3 each timeAlternative: 9 โ†’ 7 โ†’ 2 (interval: -2)๐ŸŽฏ Winning Sequence Found!Length 3: [4, 7, 10] with difference +3OR Length 3: [9, 7, 2] with difference -2Both sequences maintain perfect arithmetic progression!
Understanding the Visualization
1
Identify Patterns
Look for pairs of elements that could start an arithmetic sequence
2
Calculate Intervals
For each pair, determine the common difference (musical interval)
3
Extend Sequences
Find additional elements that continue each pattern
4
Track the Longest
Remember the longest arithmetic sequence found
Key Takeaway
๐ŸŽฏ Key Insight: Dynamic programming helps us efficiently track all possible arithmetic patterns by remembering what sequences we've already built, avoiding redundant work.
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
95.7K Views
Medium Frequency
~18 min Avg. Time
2.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