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: 14
💡 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
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 INPUT Array: nums 1 i=0 2 i=1 1 i=2 Good Subsequences: [1], [2], [1] [1,2], [2,1] [1,2,1] Consecutive diff = 1 Input Values: nums = [1, 2, 1] ALGORITHM STEPS 1 Init Hash Maps cnt[x], sum[x] for each val 2 Process Each num Check neighbors x-1, x+1 3 Update Counts cnt[x] += cnt[x-1]+cnt[x+1]+1 4 Update Sums sum[x] += sum[x-1]+sum[x+1] Hash Maps State val | cnt | sum 1 | 3 | 3 2 | 3 | 9 Total = 3 + 9 = 12 FINAL RESULT All Good Subsequences: [1] --> 1 [2] --> 2 [1] --> 1 [1,2] --> 3 [2,1] --> 3 [1,2,1] --> 4 Sum = 12 OUTPUT 12 (mod 10^9 + 7) Key Insight: Use two hash maps: cnt[x] tracks count of subsequences ending at value x, sum[x] tracks sum of elements in those subsequences. For each num, extend subsequences from neighbors (x-1, x+1) since |diff| must be 1. O(n) time complexity. TutorialsPoint - Sum of Good Subsequences | Hash Map Approach
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