medium +15 pts

Arithmetic Slices Count

Count the number of contiguous subarrays that form an arithmetic sequence.

An arithmetic slice is a contiguous subarray of length at least 3 such that the difference between consecutive elements is constant. For example, [1, 3, 5] and [1, 3, 5, 7] are arithmetic slices, but [1, 3, 6] is not. Write a function `count_arithmetic_slices(nums)` that takes a list of integers and returns the total number of arithmetic slices that exist in the list. Note: A subarray is a contiguous part of the original list. The order of the elements must be preserved.

Constraints

0 <= len(nums) <= 10^4; -10^9 <= nums[i] <= 10^9. The answer fits in a 64-bit integer.

Example

>>> count_arithmetic_slices([1, 2, 3, 4])
3
>>> count_arithmetic_slices([1])
0
>>> count_arithmetic_slices([1, 2, 3, 8, 9, 10])
2
15 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Scan the array and track the length of the current arithmetic sequence ending at each index.
If the difference between nums[i] and nums[i-1] equals the previous difference, extend the current sequence; otherwise reset.
For a sequence of length n, the number of arithmetic slices ending at the last element is n-2.
Sum the counts as you extend sequences to get the total.
Alternative: for each maximal run of equal differences of length L, add (L-1)*(L-2)//2.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.