Longest Arithmetic Subsequence of Given Difference - Problem

Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.

A subsequence is a sequence that can be derived from arr by deleting some or no elements without changing the order of the remaining elements.

Input & Output

Example 1 — Complete Sequence
$ Input: arr = [1,3,5,7], difference = 2
Output: 4
💡 Note: The entire array forms an arithmetic sequence: 1→3→5→7, where each difference is 2. Length = 4.
Example 2 — Partial Sequence
$ Input: arr = [1,2,3,4], difference = 1
Output: 4
💡 Note: The entire array forms an arithmetic sequence: 1→2→3→4, where each difference is 1. Length = 4.
Example 3 — Multiple Chains
$ Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2
Output: 4
💡 Note: The longest arithmetic sequence with difference -2 is: 7→5→3→1. Length = 4.

Constraints

  • 1 ≤ arr.length ≤ 105
  • -104 ≤ arr[i], difference ≤ 104

Visualization

Tap to expand
Longest Arithmetic Subsequence: arr=[1,3,5,7], difference=21357+2+2+2Valid arithmetic subsequence: 1 → 3 → 5 → 7Each consecutive pair differs by exactly 2Output: 4Length of longest sequence
Understanding the Visualization
1
Input
Array [1,3,5,7] with difference = 2
2
Process
Find arithmetic subsequences with difference 2
3
Output
Return length 4 (entire array forms valid sequence)
Key Takeaway
🎯 Key Insight: Use hash map to track sequence lengths ending at each number for O(n) solution
Asked in
Amazon 15 Google 12 Microsoft 8
32.0K Views
Medium Frequency
~15 min Avg. Time
845 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