Python 1218.py
class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
lengths = defaultdict(int)
for n in arr:
lengths[n] = max(lengths[n], lengths[n - difference] + 1)
return max(lengths.values())
Difficulty
and has an acceptance rate of about 55% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
- Hash Table
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the length of the longest arithmetic subsequence within a given integer array where each consecutive element differs by a fixed value. It does so by iterating through the array once, maintaining a mapping from each encountered number to the length of the longest valid subsequence that ends with that number. The final answer is the maximum value stored in this mapping.
Key Steps
Initializing the length map
lengths = defaultdict(int)
A defaultdict of integers is created so that any key not yet present returns a default value of 0. This eliminates the need for explicit existence checks when updating subsequence lengths.
Processing each element
for n in arr:
lengths[n] = max(lengths[n], lengths[n - difference] + 1)
For every number n in the input array, the algorithm looks up the length of the subsequence that would end with n - difference. Adding the current element extends that subsequence by one. The max ensures that if n has been seen before, the longer of the existing subsequence length and the newly computed one is retained.
Determining the result
return max(lengths.values())
After the loop, the dictionary holds the best lengths for all possible ending values. The maximum among them is the length of the longest arithmetic subsequence that satisfies the required difference.
Edge Cases Handled
The logic naturally accommodates arrays containing duplicate values because each occurrence updates the stored length only if it yields a longer subsequence. When the difference is zero, the expression n - difference equals n, and the update reduces to lengths[n] = max(lengths[n], lengths[n] + 1), which correctly builds a subsequence of identical elements. Negative numbers in the array or a negative difference are treated identically to positive values, as the arithmetic relationship is preserved through the subtraction operation. The use of defaultdict guarantees that references to keys that have not yet appeared (such as n - difference on the first encounter) return 0, allowing the first element of any potential subsequence to start with a length of 1.
Performance Optimizations
The algorithm achieves linear traversal of the input by avoiding nested loops; each element triggers only constant-time dictionary operations. The defaultdict eliminates conditional branches that would otherwise be required to initialize missing keys, thereby reducing overhead. Updating the dictionary in place prevents the allocation of auxiliary data structures, and the final max call scans the stored values only once after all updates are complete. These choices together ensure that the solution scales efficiently with the size of the input array.
ELI5 - Simplified Explanation
Imagine a long line of numbered building blocks sitting on the floor. The goal is to pick out a special path of blocks that follow a specific counting rule. This rule says that each block must be a certain distance away from the one before it, based on the difference number provided.
To keep track of everything, there is a magic notebook called lengths. Every time a block is picked up, it is written down in the notebook. First, the code looks at the number on the block. Then, it checks the notebook to see if there is already a sequence ending with the previous block, which would be the current number minus the difference. If there is, it adds one more to that sequence to make it longer. If not, it just counts the current block as the start of a new sequence. This happens for every single block in the line, one after another. By the end, the notebook holds the length of the longest path that follows the rule.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | JS | Go | Rust | TS | ||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 2453: Destroy Sequential Targets
Solved On The Same Day
- problem 1631: Path With Minimum Effort
- problem 329: Longest Increasing Path in a Matrix
- problem 332: Reconstruct Itinerary
- problem 1312: Minimum Insertion Steps to Make a String Palindrome
- problem 1964: Find the Longest Valid Obstacle Course at Each Position
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality