Arithmetic Slices
Medium
Topics
An arithmetic slice is a contiguous subarray of length at least 3 with a constant difference between consecutive elements. Return the number of arithmetic slices in nums.
Example 1
L by one element adds L new slices, so a single counter accumulates all 3 of them without enumerating any.Input: nums = [1,2,3,4] Output: 3
Example 2
Input: nums = [1,3,5,7,9] Output: 6
Example 3
Input: nums = [1,2,3,8,9,10] Output: 2
Constraints
- 1 <= nums.length <= 5000
- -1000 <= nums[i] <= 1000
Editorial — intuition, approach, complexity and pitfalls
Intuition
Enumerating every subarray and testing it is O(n^2) or worse. The better framing counts, for each ending index, how many arithmetic subarrays end there — then sums those counts.
The recurrence is short. If nums[i] continues the same difference as the previous pair, then every arithmetic slice ending at i-1 extends to one ending at i, and the three-element slice [i-2, i-1, i] is new. So ending_here = ending_at_previous + 1. If the difference breaks, nothing arithmetic ends at i and the count resets to 0.
Because each term depends only on the one before it, no table is needed — a single rolling counter does.
Approach
current = 0,total = 0.- From
i = 2: ifnums[i] - nums[i-1] == nums[i-1] - nums[i-2], incrementcurrentand add it tototal; else resetcurrentto 0.
Dry Run
nums = [1,2,3,4]
i=2 3-2 == 2-1 -> current 1 total 1 ([1,2,3])
i=3 4-3 == 3-2 -> current 2 total 3 ([2,3,4] and [1,2,3,4])
answer 3
nums = [1,2,3,8,9,10]
i=2 yes -> current 1 total 1
i=3 8-3=5 != 1 -> current 0
i=4 9-8 == 8-3? no, 1 != 5 -> current 0
i=5 10-9 == 9-8 -> current 1 total 2
answer 2The run of length 4 contributing 3 rather than 2 is the whole point: a longer arithmetic run contains several slices, and the running counter accumulates them without enumerating.
Complexity
- Time — O(n): one pass, against O(n^2) for checking each subarray.
- Space — O(1): two counters. A full DP array over ending indices would be O(n) and read only its previous entry.
Common Pitfalls
- Starting the loop before index 2. A slice needs three elements.
- Adding 1 per valid position rather than adding the running counter. That counts only the three-element slices and misses the longer ones.
- Not resetting
currentwhen the difference breaks, which merges unrelated runs. - Comparing against a single difference computed once at the start. The difference may change between runs.
Full Solution — all languages
class Solution:
def numberOfArithmeticSlices(self, nums):
total = cur = 0
for i in range(2, len(nums)):
if nums[i] - nums[i-1] == nums[i-1] - nums[i-2]:
cur += 1
total += cur
else:
cur = 0
return totalimport java.util.*;
class Solution {
public int numberOfArithmeticSlices(int[] nums) {
int total = 0, cur = 0;
for (int i = 2; i < nums.length; i++) {
if (nums[i] - nums[i-1] == nums[i-1] - nums[i-2]) {
cur++;
total += cur;
} else cur = 0;
}
return total;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int numberOfArithmeticSlices(vector<int>& nums) {
int total = 0, cur = 0;
for (int i = 2; i < (int)nums.size(); i++) {
if (nums[i] - nums[i-1] == nums[i-1] - nums[i-2]) {
cur++;
total += cur;
} else cur = 0;
}
return total;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var numberOfArithmeticSlices = function(nums) {
let total = 0, cur = 0;
for (let i = 2; i < nums.length; i++) {
if (nums[i] - nums[i-1] === nums[i-1] - nums[i-2]) {
cur++;
total += cur;
} else cur = 0;
}
return total;
};