Skip to main content

Longest Arithmetic Subsequence of Given Difference - Solution & Explanation

MediumArrayHash TableDynamic Programming14 min readAsked at: Meta, Google
Practice this problem

Problem Statement

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.

 

Example 1:

Input: arr = [1,2,3,4], difference = 1
Output: 4
Explanation: The longest arithmetic subsequence is [1,2,3,4].

Example 2:

Input: arr = [1,3,5,7], difference = 1
Output: 1
Explanation: The longest arithmetic subsequence is any single element.

Example 3:

Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2
Output: 4
Explanation: The longest arithmetic subsequence is [7,5,3,1].

 

Constraints:

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

Approach Overview

Problem Overview: You receive an integer array arr and a fixed integer difference. The goal is to find the length of the longest subsequence where the difference between consecutive elements is exactly difference. The subsequence does not need to be contiguous, but the order of elements must remain the same.

Approach 1: Dynamic Programming with HashMap (Time: O(n), Space: O(n))

The key observation: if a number x appears in the array, the previous value in a valid arithmetic subsequence must be x - difference. Maintain a hash map where dp[x] stores the length of the longest subsequence ending with value x. Iterate through the array once. For each value x, check if x - difference already exists in the map. If it does, extend that subsequence: dp[x] = dp[x - difference] + 1. Otherwise start a new subsequence with length 1. Update the map and track the maximum length. Hash lookups keep the operation constant time, giving a linear pass solution. This approach relies heavily on Hash Table lookups combined with Dynamic Programming state transitions.

Approach 2: Optimized Dynamic Programming with Direct Indexing (Time: O(n), Space: O(n))

If the value range of the array is reasonably bounded, the hash map can be replaced with a direct-index array. Instead of storing states in a map, use an array where the index represents the number itself (with offset if negatives exist). For each element x, compute x - difference and look up the stored subsequence length directly from the DP array. Then update the current index with the extended length. Direct indexing removes hash overhead and improves constant factors while keeping the same recurrence. This technique still follows the same Array-based dynamic programming idea but trades memory for faster access.

Recommended for interviews: The hash map dynamic programming solution is the expected answer. It demonstrates that you recognized the recurrence relationship between values and used a constant-time lookup structure. Mentioning the direct-index optimization shows deeper understanding of performance tradeoffs. Interviewers usually care most about identifying the DP state dp[x] and deriving the transition dp[x] = dp[x - difference] + 1.

Approach 1: Dynamic Programming with HashMap

This approach uses a hash map (or dictionary) to keep track of the longest subsequence length that can be achieved ending with a specific value. For each element in the array, we check if there is an arithmetic subsequence ending with the element minus the given difference. If such a subsequence exists, we calculate the current subsequence length. Otherwise, we start a new subsequence from this element.

This Python solution uses a dictionary called dp where each key is a number from the array, and the value is the longest subsequence length ending with that number. We update the dictionary by iterating through each number in arr and deciding whether we can append the current number to an existing subsequence with the specified difference.

Code

Python

C++

JavaScript

Java

C

C#

Complexity

Time Complexity: O(n), where n is the length of arr. We iterate over the array once.
Space Complexity: O(n), where n is the number of distinct elements in arr stored in the dictionary.

Try this approach in the editor →

Approach 2: Optimized Dynamic Programming with Direct Indexing

This approach utilizes an array to store information about each possible element value scaled according to the constraints. For each element in arr, determine if there is a previous subsequence that can be extended using direct array access.

This Python solution uses an indexed array to store the length of subsequences directly aligned by the values of elements. We handle negative indices by offsetting the array from the minimal possible value.

Code

Python

C++

JavaScript

Java

C

C#

Complexity

Time Complexity: O(n), where n is the length of arr.
Space Complexity: O(1) (constant size array mentioned in constraints).

Try this approach in the editor →

Approach 3: Dynamic Programming

We can use a hash table f to store the length of the longest arithmetic subsequence ending with x.

Traverse the array arr, and for each element x, update f[x] to be f[x - difference] + 1.

After the traversal, return the maximum value in f as the answer.

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the array arr.

Code

Python

Java

C++

Go

TypeScript

Rust

JavaScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Dynamic Programming with HashMap

Time Complexity: O(n), where n is the length of arr. We iterate over the array once.
Space Complexity: O(n), where n is the number of distinct elements in arr stored in the dictionary.

Optimized Dynamic Programming with Direct Indexing

Time Complexity: O(n), where n is the length of arr.
Space Complexity: O(1) (constant size array mentioned in constraints).

Dynamic Programming—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Dynamic Programming with HashMapO(n)O(n)General case. Works for any integer range and is the most common interview solution.
Optimized DP with Direct IndexingO(n)O(n)When value range is limited and you want faster constant-time lookups without hash overhead.

Video Solution

Longest Arithmetic Subsequence of Given Difference | Recur + Memo | Optimal | META | Leetcode-1218 • codestorywithMIK • 6,877 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Longest Arithmetic Subsequence of Given Difference easy or hard?
The problem is rated Medium because recognizing the dynamic programming relationship is not immediately obvious. Once the recurrence dp[x] = dp[x - difference] + 1 is identified, the implementation becomes straightforward.
Longest Arithmetic Subsequence of Given Difference Python/Java solution
Python and Java implementations follow the same idea: iterate through the array and store dp[x] = dp.get(x - difference, 0) + 1. Python typically uses a dictionary, while Java uses a HashMap<Integer, Integer>. Both achieve O(n) time complexity.
How to solve Longest Arithmetic Subsequence of Given Difference in O(n)?
Use a hash map where the key is the value in the array and the value is the length of the longest subsequence ending with that number. For each element x, compute dp[x] = dp[x - difference] + 1 if the previous value exists; otherwise start a new subsequence of length 1. Track the maximum length during the iteration.
What is the best approach for Longest Arithmetic Subsequence of Given Difference?
Dynamic programming with a hash map is the most effective approach. Store the length of the longest subsequence ending at value x using dp[x]. For each number, check whether x - difference already exists and extend that subsequence. This produces an O(n) time and O(n) space solution.
Is Longest Arithmetic Subsequence of Given Difference asked at Google/Amazon/Meta?
Arithmetic subsequence and dynamic programming problems appear frequently in interviews at companies like Amazon, Google, and Meta. Variants of this problem test understanding of hash maps, DP state transitions, and sequence pattern recognition.
What data structure is used in Longest Arithmetic Subsequence of Given Difference?
The main data structure is a hash map (dictionary) that stores dynamic programming states. Each key represents a value from the array and maps to the longest arithmetic subsequence ending with that value.
What is the time complexity of Longest Arithmetic Subsequence of Given Difference?
The optimal solution runs in O(n) time because each element is processed once with constant-time hash lookups. Space complexity is O(n) since the hash map stores subsequence lengths for encountered values.

Ready to solve this problem?

Practice Longest Arithmetic Subsequence of Given Difference with our built-in code editor and test cases.

Practice on FleetCode