Problem 1027

Abstract / Summary

Find the longest sequence of numbers in a list where the difference between consecutive elements is always the same.

Note

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

C++ 1027.cpp

class Solution {
public:
    int longestArithSeqLength(vector<int>& nums) {
        int best = 1;

        unordered_map<int, int> first;
        for (int i = 0; i < nums.size(); i++)
            if (first.count(nums[i]) == 0)
                first[nums[i]] = i;

        for (int step = -500; step <= 500; step++)
        {
            vector<bool> started(1000, false);

            for (int i = 0; i < nums.size(); i++)
            {
                if (started[nums[i]])
                    continue;
                started[nums[i]] = true;

                auto length = 1;
                auto next = nums[i] + step;

                if (first.count(next) == 0)
                    continue;

                int j = i+1;
                if (j < first[next])
                    j = first[next];

                for (; j < nums.size(); j++)
                {
                    if (next == nums[j])
                    {
                        next += step;
                        length++;
                        if (best < length)
                            best = length;

                        if (first.count(next) == 0)
                            continue;
                    }
                }
            }
        }
        return best;
    }
};

48 lines | 1323 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 49% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • 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 that can be formed from the input vector nums. An arithmetic subsequence is a sequence of numbers taken from nums (preserving order) where the difference between consecutive elements is constant. The algorithm explores all possible common differences within a bounded range and tracks the longest sequence found.

Core Logic

The function begins by initializing a variable best to 1, representing the minimum possible length of any subsequence (a single element).

int best = 1;

A hash map named first records the earliest index at which each distinct value appears in nums. This map enables quick lookup of the first occurrence of any candidate next element in the arithmetic progression.

unordered_map<int, int> first;
for (int i = 0; i < nums.size(); i++)
    if (first.count(nums[i]) == 0)
        first[nums[i]] = i;

The algorithm then iterates over every integer step from -500 to 500 inclusive. This range is chosen based on the problem’s constraints, ensuring that all feasible common differences are examined.

for (int step = -500; step <= 500; step++)
{
    // body omitted for brevity
}

Inside the step loop, a boolean vector started of size 1000 is allocated. It records whether a particular value has already been used as a starting point for the current step. This prevents redundant work when the same value would otherwise be processed multiple times.

vector<bool> started(1000, false);

The inner loop walks through each index i of nums. If the value at nums[i] has already been marked in started, the iteration skips to the next index. Otherwise, the value is marked as started, and the algorithm attempts to extend an arithmetic sequence beginning at this element with the current step.

for (int i = 0; i < nums.size(); i++)
{
    if (started[nums[i]])
        continue;
    started[nums[i]] = true;

    auto length = 1;
    auto next = nums[i] + step;
    // continuation omitted
}

If the immediate next value (next) does not exist in the first map, the algorithm cannot form a longer sequence from this start and proceeds to the next i.

if (first.count(next) == 0)
    continue;

When a candidate next does exist, the variable j is set to the index immediately after i. If this index lies before the first occurrence of next, j is advanced to that first occurrence, guaranteeing that the search begins at a position where next can actually be found.

int j = i + 1;
if (j < first[next])
    j = first[next];

A forward scan from j to the end of nums checks each element. Whenever an element matches the expected next value, the sequence length is incremented, next is advanced by step, and best is updated if the new length exceeds the current best. If the updated next value is not present in the first map, the loop continues without resetting the scan pointer, allowing the algorithm to keep looking for further matches that may appear later.

for (; j < nums.size(); j++)
{
    if (next == nums[j])
    {
        next += step;
        length++;
        if (best < length)
            best = length;

        if (first.count(next) == 0)
            continue;
    }
}

After all steps and starting positions have been examined, the function returns the maximum length discovered.

return best;

Edge Cases Handled

The implementation gracefully handles several boundary conditions:

  • Single-element input - With only one number, the outer loops still execute, but no extension is possible, leaving best at its initial value of 1, which correctly reflects the longest arithmetic subsequence length.

  • Repeated values - The first map stores only the earliest index for each distinct value, while the started vector ensures that each value is considered as a start at most once per step. This prevents redundant processing of identical values that could otherwise cause unnecessary work.

  • Negative common differences - By iterating step from -500 to 500, the algorithm naturally accommodates decreasing sequences, allowing the detection of arithmetic subsequences that descend in value.

  • Values outside the started vector range - The started vector is sized to 1000, matching the problem’s value domain (typically -500 to 500 shifted to non-negative indices). The code accesses started[nums[i]] directly, assuming that all input values fall within this range, which aligns with the problem constraints.

  • Gaps in the progression - When a required next value is missing from the map, the inner scan simply continues without resetting, effectively skipping over gaps while still preserving the possibility of later matches for the same progression.

Performance Optimizations

Several design choices contribute to the efficiency of the solution:

  • Pre-computed first occurrence map - By storing the earliest index of each value, the algorithm can jump directly to the first viable position for a needed next element, avoiding linear scans from the current index each time a new value is sought.

  • Early termination of impossible starts - The check if (first.count(next) == 0) continue; eliminates any starting point that cannot be extended even by a single step, saving the cost of a full inner scan for such cases.

  • Per-step deduplication via started - Marking values that have already been used as a start for the current step prevents the algorithm from re-evaluating identical beginnings, reducing the number of redundant inner loops.

  • Bounded step range - Limiting step to the interval [-500, 500] confines the search space to the range of differences that can actually appear given the input constraints, preventing unnecessary exploration of impossible differences.

  • Selective index advancement - Adjusting j to first[next] when the next needed value appears later in the array ensures that the scan does not waste iterations on indices that cannot possibly satisfy the progression, thereby tightening the inner loop’s workload.

Collectively, these techniques keep the runtime within acceptable limits for the intended input sizes, allowing the algorithm to explore all feasible arithmetic subsequences without excessive overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine there is a big collection of colorful blocks with numbers written on them, all lined up in a row. These blocks are like a secret puzzle where some numbers belong to a special pattern. A pattern is just a sequence of numbers that jump by the same amount every time, like counting by twos, where you go from two to four to six.

The goal is to find the longest path of these blocks that follow the same jumping rule. To do this, the computer acts like an explorer. First, it makes a little notebook to remember where it saw each number for the very first time.

Next, the computer decides to try out every single jumping rule possible. It picks a rule, which tells it how much to add to a number to find the next one in the pattern. It goes through the row of blocks one by one to see how many it can pick up that match that specific rule.

When it finds a block that fits, it adds one to its count and looks for the next block that follows the same hop. Each time it starts a new jump, it checks its notebook to see where the next jump might be hiding. It keeps track of how many blocks it found, and if this path ends up being longer than any other path found so far, it saves that number as the new record to beat. It does this over and over again until it has checked every single rule and every possible path of blocks.

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 = 4 | μ = 4.42 | σ = 1.71

Complexity Analysis

not analyzed yet

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 Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github charles-wangkai Java
everthis JS
fsq C++
Garvit244 Python
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
varunu28 Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
charles-wangkai Java
everthis JavaScript
fsq C++
Garvit244 Python
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
varunu28 Java
wisdompeak C++
31 links | 17 authors | 7 languages

Videos

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

Similar Problems

2 similar problems

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 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