Arithmetic Slices (LeetCode 413): Solution and Explanation

Medium
Array
Dynamic Programming
Sliding Window

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

  1. Set total = 0 and curr = 0.
  2. For each i from 2 to n - 1, compare nums[i] - nums[i-1] with nums[i-1] - nums[i-2].
  3. If they are equal, increase curr by one and add it to total.
  4. Otherwise reset curr to 0, since no arithmetic slice can end at i.
  5. Return total after the loop.

Step-by-step example

nums = [1,2,3,4]
  1. Start with total = 0, curr = 0.
  2. i = 2: the steps 2 - 1 and 3 - 2 are both 1, so curr = 1 (the slice [1,2,3]) and total = 1.
  3. 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.
  4. 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 total
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each index is compared once with its two predecessors.

Space

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 curr when 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.