mediumDynamic ProgrammingDynamic Programming

Arithmetic Slices

mediumTime: O(n)Space: O(1)

Signals to notice

count subarrays forming arithmetic sequencecommon difference between consecutive elementsextend or break

Brute force first

Check every subarray for arithmetic property. Each subarray is independently validated. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

DP: dp[i] = number of arithmetic slices ending at index i. If nums[i] - nums[i-1] == nums[i-1] - nums[i-2], then dp[i] = dp[i-1] + 1 (extend the sequence). Otherwise dp[i] = 0. Sum all dp values. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

What must stay true

Each new element either extends the current arithmetic run (same common difference) or breaks it. When it extends, it adds dp[i-1] + 1 new slices — the previous count plus one new slice ending at i. As long as that statement keeps holding, you can trust the steps built on top of it.

Easy way to go wrong

Not understanding why dp[i] = dp[i-1] + 1 — extending a run of length k creates one additional slice of each length from 3 to k+1. The +1 accounts for the new minimum-length slice. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Dynamic Programming Pattern