Sum of Good Subsequences - Problem

You're given an integer array nums and need to find all "good subsequences" - but what makes a subsequence good?

A good subsequence is one where each pair of consecutive elements has an absolute difference of exactly 1. Think of it like a staircase where each step is exactly one unit up or down!

Your task: Calculate the sum of all elements in all possible good subsequences. Since this number can be astronomically large, return the result modulo 109 + 7.

Key insights:

  • A single element is always a good subsequence
  • Elements don't need to be adjacent in the original array
  • Focus on consecutive differences in the subsequence, not original positions

Example: For [1, 2, 1], good subsequences include [1], [2], [1], [1,2], [2,1], and [1,2,1].

Input & Output

example_1.py โ€” Basic Case
$ Input: [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.py โ€” Single Element
$ Input: [3]
โ€บ Output: 3
๐Ÿ’ก Note: Only one good subsequence possible: [3] with sum = 3
example_3.py โ€” No Adjacent Differences
$ Input: [1, 3, 5]
โ€บ Output: 9
๐Ÿ’ก Note: No consecutive elements differ by 1, so only single-element subsequences are good: [1], [3], [5]. Total: 1+3+5 = 9

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 105
  • A subsequence of size 1 is always considered good
  • Return the result modulo 109 + 7

Visualization

Tap to expand
๐ŸŽต Musical Sequence BuildingInput Notes: [1, 2, 1]121๐ŸŽผ Processing Each Note:Note 1 (First)Creates melody: [1]dp[1] = count:1, sum:1Total value: 1Note 2Extends [1] โ†’ [1,2]Creates solo [2]dp[2] = count:2, sum:4Note 1 (Again)Extends [2] โ†’ [2,1]Extends [1,2] โ†’ [1,2,1]dp[1] = count:3, sum:6๐ŸŽฏ Final Result: All Valid MelodiesGood Subsequences (Melodies):Solo notes: [1], [2], [1] โ†’ sum = 4Two-note melodies: [1,2], [2,1] โ†’ sum = 6Three-note melody: [1,2,1] โ†’ sum = 4Total Musical Value: 14
Understanding the Visualization
1
Track Melody Endings
For each note value, remember how many melodies end there and their total value
2
Extend Compatible Melodies
When we see a new note, extend melodies ending one semitone away (ยฑ1)
3
Update State
Add the new note as both a solo melody and extension of existing ones
4
Accumulate Value
Sum all melody values created so far
Key Takeaway
๐ŸŽฏ Key Insight: Instead of generating all melodies explicitly, we track how many melodies end at each note and their total value, then efficiently extend compatible melodies as we encounter new notes!
Asked in
Google 42 Amazon 38 Meta 35 Microsoft 29
43.4K Views
Medium-High Frequency
~25 min Avg. Time
1.8K 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