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 INPUT Array nums: 2 i=0 4 i=1 6 i=2 8 i=3 Valid Subsequences: [2, 4, 6] diff=2 [4, 6, 8] diff=2 [2, 4, 6, 8] diff=2 Need at least 3 elements with constant difference ALGORITHM (DP) 1 Initialize DP dp[i] = HashMap(diff --> count) 2 For each pair (i,j) Calculate diff = nums[i]-nums[j] 3 Update counts dp[i][diff] += dp[j][diff] + 1 4 Accumulate result result += dp[j][diff] DP State (diff=2): Index 0 1 2 3 d=2 0 1 2 3 Count extends previous APs by same difference FINAL RESULT Arithmetic Subsequences Found: 3 Breakdown: [2,4,6] diff=2, len=3 [4,6,8] diff=2, len=3 [2,4,6,8] diff=2, len=4 OK Key Insight: Use a DP array where dp[i] is a HashMap storing (difference --> count of weak APs ending at i). A "weak AP" has length >= 2. When extending a weak AP of length 2+, we get a valid AP (length >= 3). Time: O(n^2), Space: O(n^2) - counts all pairs and their common differences efficiently. TutorialsPoint - Arithmetic Slices II - Subsequence | Dynamic Programming Approach
Asked in
Google 15 Facebook 12 Amazon 8
67.6K 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