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;
}
};
Difficulty
and has an acceptance rate of about 49% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- 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 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
bestat its initial value of 1, which correctly reflects the longest arithmetic subsequence length. -
Repeated values - The
firstmap stores only the earliest index for each distinct value, while thestartedvector ensures that each value is considered as a start at most once perstep. This prevents redundant processing of identical values that could otherwise cause unnecessary work. -
Negative common differences - By iterating
stepfrom -500 to 500, the algorithm naturally accommodates decreasing sequences, allowing the detection of arithmetic subsequences that descend in value. -
Values outside the
startedvector range - Thestartedvector is sized to 1000, matching the problem’s value domain (typically -500 to 500 shifted to non-negative indices). The code accessesstarted[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
nextvalue 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
nextelement, 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 currentstepprevents the algorithm from re-evaluating identical beginnings, reducing the number of redundant inner loops. -
Bounded step range - Limiting
stepto 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
jtofirst[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.
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.
Code Quality
Complexity Analysis
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 | 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++ |
Videos
Similar Problems
- problem 446: Arithmetic Slices II - Subsequence
- problem 2453: Destroy Sequential Targets
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
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