Sum of Good Subsequences - Problem

You are given an integer array nums. A good subsequence is defined as a subsequence of nums where the absolute difference between any two consecutive elements in the subsequence is exactly 1.

Return the sum of all possible good subsequences of nums. Since the answer may be very large, return it modulo 10^9 + 7.

Note that a subsequence of size 1 is considered good by definition.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,1]
Output: 12
💡 Note: Good subsequences: [1] (sum=1), [2] (sum=2), [1] (sum=1), [1,2] (sum=3), [2,1] (sum=3), [1,2,1] (sum=4). Total: 1+2+1+3+3+4 = 14. Wait, let me recalculate: [1]=1, [2]=2, [1]=1, [1,2]=3, [2,1]=3. Total = 1+2+1+3+3 = 10. Actually for [1,2,1]: we have multiple [1] at positions 0,2, [2] at position 1, [1,2] using positions 0,1, [2,1] using positions 1,2. Sum = 1+2+1+3+3 = 10.
Example 2 — Single Element
$ Input: nums = [3]
Output: 3
💡 Note: Only one good subsequence: [3] with sum 3
Example 3 — No Extensions
$ Input: nums = [1,3,5]
Output: 9
💡 Note: No consecutive elements differ by exactly 1. Good subsequences are only single elements: [1], [3], [5]. Total: 1+3+5 = 9

Constraints

  • 1 ≤ nums.length ≤ 105
  • -105 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Sum of Good Subsequences: [1,2,1]121index 0index 1index 2Good Subsequences:[1] = 1[2] = 2[1] = 1[1,2] = 3[2,1] = 3[1,2,1] = 4|2-1|=1 ✓|1-2|=1 ✓Calculation:Single elements: 1 + 2 + 1 = 4Pairs: 3 + 3 = 6Triple: 4Total Sum: 4 + 6 + 4 = 14Answer: 14
Understanding the Visualization
1
Input
Array [1,2,1] with elements that can form good subsequences
2
Process
Find all subsequences where |a[i] - a[i+1]| = 1
3
Output
Sum all valid subsequences: 1+2+1+3+3+4 = 14
Key Takeaway
🎯 Key Insight: Use DP to track subsequences ending at each value, extending those at val±1
Asked in
Google 15 Amazon 12 Microsoft 8
15.4K Views
Medium Frequency
~35 min Avg. Time
284 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