Arithmetic Slices II - Subsequence

HardDynamic Programming1d dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A sequence is **arithmetic** if it has at least three elements and every pair of consecutive elements differs by the same amount. [1, 3, 5, 7], [7, 7, 7] and [3, -1, -5, -9] are arithmetic; [1, 1, 2, 5, 7] is not. Given an integer array nums, return the number of subsequences of nums that are arithmetic. A subsequence keeps the original relative order but may skip elements. Two subsequences are different if they use a different set of **indices**, even when their values match. The answer fits in a signed 32-bit integer. Differences between elements can overflow 32 bits, so compute them with 64-bit arithmetic. Aim for O(n^2) time.

Examples

Input: nums = [2,4,6,8,10]
Output: 7
The arithmetic subsequences are [2,4,6], [4,6,8], [6,8,10], [2,4,6,8], [4,6,8,10], [2,4,6,8,10] and [2,6,10].
Input: nums = [7,7,7,7,7]
Output: 16
Any choice of at least 3 of the 5 indices works: C(5,3) + C(5,4) + C(5,5) = 10 + 5 + 1 = 16.

Constraints

  • 1 <= nums.length <= 1000
  • -2^31 <= nums[i] <= 2^31 - 1
  • The answer fits in a signed 32-bit integer

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More 1d dp problems