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

Arithmetic Slices II - Subsequence

HardDynamic programming

You get an array of whole numbers, nums. Count its arithmetic subsequences: picks of at least three elements, kept in their original order, where every two neighbouring picks differ by the same amount.

A subsequence may skip elements, so [1, 5, 9] is one in [1, 2, 5, 3, 9]. Two picks count separately when they use different positions, even if the values match. The answer always fits in a 32-bit integer.

Example 1

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

Example 2

Input:  nums = [4, 4, 4, 4]
Output: 5
Why:    four picks of 3 and one of 4, step 0

Example 3

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

Constraints

  • 1 ≤ length of nums ≤ 1,000
  • −2³¹ ≤ nums[i] ≤ 2³¹ − 1
  • The answer fits in a 32-bit signed integer

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 every pair (memo)O(n³)
  2. DP on end and stepO(n²)

The idea in one sentence

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

Side by side

ApproachTimeRelative work for 1,000 numbersVerdict
Extend every pair (memo)O(n³)
Correct; too slow at the limit
DP on end and stepO(n²)
Best; one update per pair

n = length of nums.

Edge cases to test

  • Fewer than three numbers. [5, 1] or [9] has no answer: return 0.
  • Repeated values. [4, 4, 4, 4] has step 0 and gives 5: every pick of 3 or 4 positions counts.
  • Overflowing steps. [2147483647, −2147483647, −2147483645] looks like step 2 in 32-bit math, but the true steps differ: the answer is 0.
  • Skipped elements. In [2, 8, 4, 9, 6, 1], [2, 4, 6] counts even though 8 and 9 sit between.

Common mistakes

  • Counting runs of length 2 as answers, instead of only the runs that grow to 3 or more.
  • Computing the step in 32-bit integers, so far-apart values wrap around and match falsely.
  • Reading ends[i][d] after writing it in the same pair, which double-counts when values repeat.

How to talk through it

  1. 1Clarify. Subsequence, not subarray? Do equal values at different positions count separately? How big can values get?
  2. 2Start from pairs. A pair fixes the step; counting extensions with a memo gives O(n³).
  3. 3Define the state. ends[i][d] = runs of 2+ ending at i with step d; say why length 2 must be tracked.
  4. 4Code the pair loop. Answer += ends[j][d]; ends[i][d] += ends[j][d] + 1. Use 64-bit steps.
  5. 5Test out loud. Run [1, 3, 5, 7] by hand to get 3, then [4, 4, 4, 4] to get 5.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?