Python 0446.py
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
result = 0
size = len(nums)
seqs = defaultdict(int)
for i in range(size):
for j in range(i):
diff = nums[i] - nums[j]
have = seqs[(j, diff)]
seqs[(i, diff)] += have + 1 # extend sequence by one element
result += have # can be zero => less than three elements
return result
Difficulty
and has an acceptance rate of about 55% (300k+ 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 number of arithmetic subsequences of length three or more that can be formed from a given list of integers. An arithmetic subsequence is defined by a constant difference between consecutive elements. The algorithm iterates over all pairs of indices, records the count of subsequences ending at each index with a particular difference, and aggregates the total count of valid subsequences.
Key Steps
The function begins by initializing a result accumulator and determining the size of the input list.
result = 0
size = len(nums)
A dictionary with default integer values is created to store the number of subsequences that end at a specific index with a given difference.
seqs = defaultdict(int)
The outer loop selects the current endpoint of a potential subsequence.
for i in range(size):
The inner loop iterates over all earlier positions to form a pair and compute the difference between the two elements.
for j in range(i):
diff = nums[i] - nums[j]
The algorithm retrieves the count of existing subsequences that end at the earlier index j with the same difference. This count represents how many ways the current pair can extend previously identified subsequences.
have = seqs[(j, diff)]
The dictionary entry for the current endpoint i and the computed difference is updated by adding the number of extensions (have) plus one for the new two-element pair itself.
seqs[(i, diff)] += have + 1
Only the extensions that already have at least two elements contribute to the final answer, because a valid arithmetic subsequence must contain three or more elements. Therefore the result accumulator is increased by the number of existing subsequences (have).
result += have
After all pairs have been processed, the accumulated result is returned.
return result
Edge Cases
When the input list is empty or contains fewer than three elements, the nested loops execute zero or minimal iterations, and the result remains zero, correctly indicating that no arithmetic subsequence of the required length exists. The use of defaultdict(int) ensures that any lookup for a non-existent key yields zero, so the algorithm gracefully handles cases where no prior subsequence with a particular difference has been recorded.
The code also accommodates negative differences and large integer values because the difference is computed using Python’s arbitrary-precision arithmetic. Duplicate values in the list generate a difference of zero, and the dictionary key (index, 0) correctly tracks subsequences with a constant zero difference, allowing the algorithm to count arithmetic subsequences formed by repeated numbers.
Performance Optimizations
The solution avoids recomputing the same difference for a given pair by storing the count directly in a hash map keyed by the tuple (index, diff). This enables constant-time retrieval and update of the number of subsequences associated with each difference at a specific endpoint. By incrementally building on previously computed counts (have + 1), the algorithm eliminates the need for explicit enumeration of all possible subsequences, reducing the overall work to a double loop over index pairs.
Using defaultdict(int) eliminates explicit existence checks before updating the dictionary, streamlining the inner loop body. The accumulation of the final answer (result += have) occurs during the same iteration that updates the dictionary, which prevents a separate pass over the data structure and thus saves additional traversal time.
ELI5 - Simplified Explanation
Imagine you have a long row of numbered building blocks. The goal is to find all the special patterns where the distance between the numbers is always the same. Think of it like jumping over hopscotch squares where each jump is the exact same size.
The code starts by looking at every block in the row one by one. It picks a block and looks back at all the blocks that came before it. It figures out the gap between the current block and the previous one. Then, it checks a little notebook it keeps to see if that same jump happened before.
If there was a previous jump, this block can join that group to make it even longer. Each time a new block joins a line, the code remembers that a new group has been created. It keeps track of all these growing lines of blocks. By the time it finishes looking at every possible pair of blocks, it knows exactly how many of these special patterns exist in the whole row.
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++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Python | Go | TS | |||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | black-shadows | C++ | ||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fpdjsns | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| yuanliu666 | Kotlin | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fpdjsns | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| yuanliu666 | Kotlin |
Videos
Similar Problems
- problem 413: Arithmetic Slices
- problem 1027: Longest Arithmetic Subsequence
Solved On The Same Day
- problem 930: Binary Subarrays With Sum
- problem 1190: Reverse Substrings Between Each Pair of Parentheses
- problem 1219: Path with Maximum Gold
- problem 1235: Maximum Profit in Job Scheduling
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