Sum of Consecutive Subsequences - Problem

Imagine you're analyzing stock price patterns where consecutive sequences represent trending periods. A sequence is consecutive if it's either:

  • Increasing: Each element is exactly 1 more than the previous (arr[i] - arr[i-1] == 1)
  • Decreasing: Each element is exactly 1 less than the previous (arr[i] - arr[i-1] == -1)

For example: [3, 4, 5] is consecutive (increasing) with value 12, and [9, 8] is consecutive (decreasing) with value 17. However, [3, 4, 3] and [8, 6] are not consecutive.

Goal: Find the sum of values of all consecutive non-empty subsequences (not subarrays) in the given array. Since the result can be massive, return it modulo 109 + 7.

Note: A single element is always considered consecutive.

Input & Output

example_1.py โ€” Basic Consecutive Sequences
$ Input: [1, 2, 4, 3]
โ€บ Output: 20
๐Ÿ’ก Note: Consecutive subsequences: [1]=1, [2]=2, [4]=4, [3]=3, [1,2]=3, [4,3]=7. Total: 1+2+4+3+3+7=20
example_2.py โ€” Single Element
$ Input: [5]
โ€บ Output: 5
๐Ÿ’ก Note: Only one subsequence possible: [5] with value 5
example_3.py โ€” No Multi-Element Consecutives
$ Input: [1, 3, 5, 7]
โ€บ Output: 16
๐Ÿ’ก Note: No consecutive subsequences of length > 1 possible. Only singles: [1]=1, [3]=3, [5]=5, [7]=7. Total: 1+3+5+7=16

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • -109 โ‰ค nums[i] โ‰ค 109
  • Answer fits in 32-bit integer after modulo operation
  • Return result modulo 109 + 7

Visualization

Tap to expand
๐Ÿ—๏ธ Staircase Pattern RecognitionInput Sequence: [1, 2, 4, 3]1243+1-1Valid Staircase Patterns Found:[1] = 1[2] = 2[4] = 4[3] = 3[1,2] = 3[4,3] = 7๐ŸŽฏ Key Insight: Dynamic Programming MagicTrack sequences ending at each floor level - when we reach floor X,we can extend all staircases ending at floors X-1 (going up) and X+1 (going down)Total Inspection Score: 1 + 2 + 4 + 3 + 3 + 7 = 20Time: O(n), Space: O(n) - Optimal Solution! ๐Ÿš€
Understanding the Visualization
1
Identify Patterns
Scan through floor levels and identify which ones can form valid staircases
2
Track Endpoints
For each floor level, remember how many staircases end there and their total heights
3
Extend Sequences
When processing a new floor, extend existing staircases that can reach it (differ by ยฑ1)
4
Accumulate Results
Sum up all staircase heights to get the final inspection score
Key Takeaway
๐ŸŽฏ Key Insight: Use dynamic programming to track consecutive sequences by their endpoints. For each element, extend existing sequences that can reach it (differ by ยฑ1) and start new single-element sequences. This avoids generating all 2^n subsequences explicitly!
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
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