Longest Arithmetic Subsequence of Given Difference — LeetCode 1218 Python Solution
- Problem
- #1218
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.