Longest Arithmetic Subsequence of Given Difference — LeetCode 1218 Python Solution

MediumArrayHash TableDynamic Programming
Problem
#1218
Reading time
2 min

The 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.

Example

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

Python solution

Python
class Solution:
    def longestSubsequence(self, arr: List[int], difference: int) -> int:
        f = defaultdict(int)
        for x in arr:
            f[x] = f[x - difference] + 1
        return max(f.values())

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1218. Longest Arithmetic Subsequence of Given Difference is filed here because LeetCode tags it Dynamic Programming, which is the vocabulary this hub collects.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1218. Longest Arithmetic Subsequence of Given Difference?
LeetCode 1218. Longest Arithmetic Subsequence of Given Difference is rated Medium on LeetCode.
What is the time complexity of LeetCode 1218. Longest Arithmetic Subsequence of Given Difference?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1218. Longest Arithmetic Subsequence of Given Difference?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1218. Longest Arithmetic Subsequence of Given Difference cover?
LeetCode 1218. Longest Arithmetic Subsequence of Given Difference is tagged Array, Hash Table and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview