Arithmetic Slices II - Subsequence - Problem

Given an integer array nums, return the number of all the arithmetic subsequences of nums.

A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences.

For example, [1, 1, 2, 5, 7] is not an arithmetic sequence.

A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.

For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].

The test cases are generated so that the answer fits in 32-bit integer.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,4,6,8]
Output: 3
💡 Note: Three arithmetic subsequences: [2,4,6], [4,6,8], and [2,4,6,8]. All have difference of 2.
Example 2 — Single Element Repeated
$ Input: nums = [7,7,7,7]
Output: 4
💡 Note: All subsequences of length ≥3 are arithmetic with difference 0: [7,7,7] appears in 4 different ways, plus [7,7,7,7].
Example 3 — No Valid Subsequences
$ Input: nums = [2,3,5]
Output: 0
💡 Note: Only one subsequence of length 3: [2,3,5]. Differences are 1 and 2, so not arithmetic.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -2³¹ ≤ nums[i] ≤ 2³¹ - 1

Visualization

Tap to expand
Arithmetic Slices II - Subsequence Problem2468Find all arithmetic subsequences (length ≥ 3)[2,4,6] diff=2[4,6,8] diff=2[2,4,6,8] diff=2All have consistent difference of 2Output: 3 arithmetic subsequences found
Understanding the Visualization
1
Input Array
Given array [2,4,6,8] with elements at different positions
2
Find Patterns
Identify arithmetic subsequences with consistent differences
3
Count Result
Total count of valid arithmetic subsequences of length ≥ 3
Key Takeaway
🎯 Key Insight: Use DP to track sequences by their differences, extending existing patterns efficiently
Asked in
Google 15 Facebook 12 Amazon 8
67.5K Views
Medium Frequency
~35 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen