Arithmetic Slices (LeetCode 413): Solution and Explanation
Given an integer array, count the contiguous subarrays of length three or more whose consecutive elements all differ by the same step.
Intuition
A subarray is arithmetic exactly when every step nums[k] - nums[k-1] inside it is the same. So the question is really about runs of equal steps.
Group the slices by the index where they end. If the step into i equals the step into i - 1, every arithmetic slice that ended at i - 1 stays arithmetic when it grows by one element, and the three elements i-2, i-1, i form one brand new slice.
That gives curr(i) = curr(i - 1) + 1 when the steps match and curr(i) = 0 when they do not. Adding curr at every index counts each slice exactly once, at its last element.
Approach: One pass counting slices by end index
- Set
total = 0andcurr = 0. - For each
ifrom 2 to n - 1, comparenums[i] - nums[i-1]withnums[i-1] - nums[i-2]. - If they are equal, increase
currby one and add it tototal. - Otherwise reset
currto 0, since no arithmetic slice can end ati. - Return
totalafter the loop.
Step-by-step example
nums = [1,2,3,4]
- Start with
total = 0,curr = 0. - i = 2: the steps 2 - 1 and 3 - 2 are both 1, so
curr = 1(the slice [1,2,3]) andtotal = 1. - i = 3: the step 4 - 3 is also 1, so
curr = 2. The slices ending here are [2,3,4] and [1,2,3,4].total = 3. - The loop ends and the answer is 3.
Code: Python, Java, C++
1class Solution:
2 def numberOfArithmeticSlices(self, nums: List[int]) -> int:
3 total = curr = 0
4 for i in range(2, len(nums)):
5 if nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]:
6 curr += 1
7 total += curr
8 else:
9 curr = 0
10 return total1class Solution {
2 public int numberOfArithmeticSlices(int[] nums) {
3 int total = 0, curr = 0;
4 for (int i = 2; i < nums.length; i++) {
5 if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) {
6 curr++;
7 total += curr;
8 } else {
9 curr = 0;
10 }
11 }
12 return total;
13 }
14}1class Solution {
2public:
3 int numberOfArithmeticSlices(vector<int>& nums) {
4 int total = 0, curr = 0;
5 for (int i = 2; i < (int)nums.size(); i++) {
6 if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) {
7 curr++;
8 total += curr;
9 } else {
10 curr = 0;
11 }
12 }
13 return total;
14 }
15};Time and space complexity
O(n)
Each index is compared once with its two predecessors.
O(1)
Only curr and total are stored.
Other approaches
Run lengths (time O(n), space O(1))
Find each maximal run of equal steps. A run of length L (in elements) holds (L - 1)(L - 2) / 2 arithmetic slices, so add that for every run.
DP array (time O(n), space O(n))
Store dp[i], the number of slices ending at i, in an array and sum it at the end. Same recurrence, but O(n) memory.
Check every subarray (time O(n^2), space O(1))
For each start, extend the end while the step stays equal and count every length of three or more. Simple but quadratic.
Common mistakes
- Counting runs instead of slices. A run of five elements contains 6 slices, not 1.
- Forgetting to reset
currwhen the step changes, which lets slices leak across a break. - Starting the loop at index 0 or 1 and reading
nums[-1]or out of bounds; a slice needs three elements, so start at 2. - Treating length-two pieces as slices. The problem requires at least three elements.
Frequently asked questions
Why does curr grow by exactly one when the step matches?
Every slice that ended at i - 1 can be extended to i, which keeps the count, and the three elements ending at i form one extra slice that did not exist before.
Is a constant array like [7,7,7] arithmetic?
Yes. The common difference is 0, so every subarray of length three or more counts.
Can the answer overflow a 32-bit integer?
No. With 5000 elements the largest count is 4998 * 4999 / 2, about 12.5 million.
How is this different from Arithmetic Slices II?
Part II asks for subsequences, which can skip elements, so it needs a hash map per index. This problem only counts contiguous subarrays.