Problem 446

Abstract / Summary

Given a sequence of numbers find the number of arithmetic subsequences of length at least three.

Note

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

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
16 lines | 502 bytes | submitted January 7, 2024 | GitHub   16% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 55% (300k+ 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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.12 | σ = 1.31

Complexity Analysis

Time: polynomial
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++ 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
33 links | 20 authors | 9 languages

Videos

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

Similar Problems

2 similar problems

Solved On The Same Day

5 solutions   January 7, 2024

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