Skip to content
Problem 413 · LeetCode 413(opens in a new tab)

Arithmetic Slices

MediumArrays

A list of numbers is arithmetic when it has at least three numbers and the gap between each number and the next is always the same, such as [2, 4, 6] or [9, 9, 9] or [5, 1, -3].

Given an integer array nums, count how many of its contiguous pieces (subarrays) are arithmetic.

Example 1

Input:  nums = [3, 5, 7, 9, 2, 2, 2]
Output: 4
Why:    [3, 5, 7], [5, 7, 9], [3, 5, 7, 9] and [2, 2, 2]
2 more examples and the constraints

Example 2

Input:  nums = [8, 1]
Output: 0
Why:    fewer than three numbers

Example 3

Input:  nums = [10, 7, 4, 1, 1]
Output: 3
Why:    [10, 7, 4], [7, 4, 1] and [10, 7, 4, 1]; the gap may be negative

Constraints

  • 1 ≤ length of nums ≤ 5,000
  • −1,000 ≤ nums[i] ≤ 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Extend from every startO(n²)
  2. Count per runO(n)
  3. Slices ending hereO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 5,000 equal numbersVerdict
Extend from every startO(n²)
Re-checks the same gaps
Count per runO(n)
Passes; mind the seams
Slices ending hereO(n)
Best; one simple loop

n = length of nums.

Edge cases to test

  • Fewer than three numbers. [8, 1] or [1] has no slice; the loop from i = 2 never runs.
  • All equal. A gap of 0 counts: [6, 6, 6, 6, 6] has 6 slices.
  • Negative gaps. [10, 7, 4, 1] has gap −3 and 3 slices.
  • Runs sharing a number. [1, 2, 3, 5, 7, 9]: 3 belongs to both runs, giving 1 + 3 = 4.

Common mistakes

  • Counting runs of two numbers, or starting the loop at i = 1.
  • Adding 1 per arithmetic index instead of cur, which misses the longer slices.
  • Starting the next run at j + 1 and losing slices that begin on the shared border number.

How to talk through it

  1. 1Clarify. Slices must be contiguous and at least three long? Does a gap of 0 count?
  2. 2Give the brute force. Extend from each start while the gap holds: O(n²) on one long run.
  3. 3Count by the last index. Slices ending at i are the ones ending at i − 1, stretched, plus one triple.
  4. 4Code the one pass. Keep cur and total; reset cur when the gap breaks.
  5. 5Test out loud. Run [1, 2] for 0, all-equal numbers, and two runs that share a number.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?