Longest Arithmetic Subsequence of Given Difference - Problem
You're given an integer array arr and an integer difference. Your task is to find the longest arithmetic subsequence where consecutive elements have exactly the specified difference.
An arithmetic subsequence is a sequence where each element differs from the previous one by a constant value. A subsequence maintains the original order of elements but allows skipping elements.
Example: In array [1, 3, 5, 7] with difference = 2, the entire array forms an arithmetic subsequence of length 4, since each element is 2 more than the previous: 1→3→5→7.
Goal: Return the length of the longest such subsequence.
Input & Output
example_1.py — Basic Sequence
$
Input:
arr = [1,2,3,4], difference = 1
›
Output:
4
💡 Note:
The entire array forms an arithmetic sequence with difference 1: 1→2→3→4. Each element differs from the previous by exactly 1.
example_2.py — Sparse Sequence
$
Input:
arr = [1,3,5,7], difference = 2
›
Output:
4
💡 Note:
The entire array forms an arithmetic sequence with difference 2: 1→3→5→7. Each element differs from the previous by exactly 2.
example_3.py — Mixed Elements
$
Input:
arr = [1,5,7,8,5,3,4,2,1], difference = -2
›
Output:
4
💡 Note:
The longest sequence with difference -2 is: 7→5→3→1. This subsequence maintains the original order and each element is 2 less than the previous.
Constraints
- 1 ≤ arr.length ≤ 105
- -104 ≤ arr[i], difference ≤ 104
- Array elements can be negative, zero, or positive
Visualization
Tap to expand
Understanding the Visualization
1
Encounter Element
For each array element, we ask: 'Can I extend an existing chain?'
2
Look Backward
Check if (current_number - difference) has an existing chain
3
Extend or Start
If found, extend that chain by 1; otherwise start a new chain of length 1
4
Update Records
Store the new chain length for the current number and track the maximum
Key Takeaway
🎯 Key Insight: Instead of trying every possible starting point (O(n²)), we build chains by looking backward for predecessors. Each element can extend at most one existing chain, making this O(n) optimal.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code