Problem 1218

Abstract / Summary

Find the longest subsequence where each pair of consecutive elements differs by a given number.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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())
7 lines | 260 bytes | submitted September 17, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 55% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
  • Hash Table
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.33 | σ = 0.98

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
25 links | 12 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

6 solutions   September 17, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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