Python 0413.py
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
size = len(nums)
result = 0
for left in range(size - 1):
delta = nums[left + 1] - nums[left]
for right in range(left + 1, size):
if delta != nums[right] - nums[right - 1]:
break
if right - left >= 2:
result += 1
return result
Difficulty
and has an acceptance rate of about 65% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
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 defines a class Solution with a method numberOfArithmeticSlices that counts the number of contiguous sub-arrays of length at least three that form an arithmetic progression. The algorithm iterates over all possible left boundaries of a slice, determines the common difference for the first two elements, and then expands the right boundary while the difference remains constant. Each time a slice of length three or more is confirmed, the result counter is incremented.
Key Steps
The method begins by measuring the length of the input list.
size = len(nums)
A variable result is initialized to accumulate the total count of arithmetic slices.
result = 0
The outer loop selects each possible starting index left except the last element, because at least two elements are needed to define a difference.
for left in range(size - 1):
Inside the outer loop, the common difference delta is computed from the first two elements of the candidate slice.
delta = nums[left + 1] - nums[left]
The inner loop moves a right pointer right from the element immediately after left + 1 to the end of the list, checking whether the current pair continues the arithmetic progression.
for right in range(left + 1, size):
if delta != nums[right] - nums[right - 1]:
break
When the difference matches, the algorithm verifies that the current window length is at least three (right - left >= 2). If so, the slice is counted.
if right - left >= 2:
result += 1
After all possible left boundaries have been examined, the accumulated count is returned.
return result
Edge Cases Handled
When the input list contains fewer than three elements, the outer loop still executes but the inner condition right - left >= 2 never becomes true, resulting in a return value of zero. This correctly reflects that no arithmetic slice can exist in such short arrays.
If the list contains repeated values, the computed difference delta becomes zero. The inner loop continues as long as subsequent differences are also zero, thereby counting slices formed by constant sequences.
The break statement inside the inner loop ensures that once a mismatch in difference is encountered, the algorithm stops extending the current slice. This prevents counting non-arithmetic extensions and correctly handles cases where the progression changes partway through a potential slice.
Performance Optimizations
The algorithm avoids constructing explicit sub-array objects; it works directly with index arithmetic, which reduces memory overhead. By breaking out of the inner loop as soon as the common difference fails, the method prevents unnecessary comparisons for the remainder of the array, limiting work to the maximal contiguous arithmetic segment that starts at each left. This early termination reduces the total number of iterations compared to a naïve triple-nested approach that would examine every possible triple independently. The use of simple integer arithmetic for difference calculation also contributes to low constant-time overhead per iteration.
ELI5 - Simplified Explanation
Imagine a long line of numbered building blocks sitting on the floor. This code acts like a little detective looking for specific patterns in how these numbers change.
First, the detective figures out how many blocks there are in total. Then, the detective picks a starting block and looks at the very next one to see how much the number grows or shrinks. This difference is like a secret rule that must stay the same for the whole group.
The detective starts walking down the line of blocks. For every new block, the detective checks if the difference between it and the previous block is the same as the secret rule. If the number jumps or dips in a way that breaks the pattern, the detective stops looking in that direction and moves on.
Whenever the detective finds a group of at least three blocks in a row that follow this steady pattern, a little count goes up by one. The detective keeps doing this over and over again, starting from every possible spot in the line, to make sure every single group that follows the rule gets counted. Eventually, the detective reaches the end of the line after investigating all the possible rows.
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++ | 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 | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JS | |||||||||
| fpdjsns | C++ | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| yuanliu666 | Kotlin | |||||||||
| zfang399 | 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 | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JavaScript | |||||||||
| fpdjsns | C++ | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| yuanliu666 | Kotlin | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 446: Arithmetic Slices II - Subsequence
Solved On The Same Day
- problem 257: Binary Tree Paths
- problem 551: Student Attendance Record I
- problem 605: Can Place Flowers
- problem 236: Lowest Common Ancestor of a Binary Tree
- problem 289: Game of Life
- problem 397: Integer Replacement
- problem 525: Contiguous Array
- problem 567: Permutation in String
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