Sum of Consecutive Subsequences - Problem

We call an array consecutive if one of the following holds:

  • arr[i] - arr[i - 1] == 1 for all 1 <= i < n (strictly increasing by 1)
  • arr[i] - arr[i - 1] == -1 for all 1 <= i < n (strictly decreasing by 1)

The value of an array is the sum of its elements.

For example, [3, 4, 5] is a consecutive array of value 12 and [9, 8] is another of value 17. While [3, 4, 3] and [8, 6] are not consecutive.

Given an array of integers nums, return the sum of the values of all consecutive non-empty subsequences. Since the answer may be very large, return it modulo 10⁹ + 7.

Note that an array of length 1 is also considered consecutive.

Input & Output

Example 1 — Basic Consecutive Sequences
$ Input: nums = [1,2,4]
Output: 10
💡 Note: Consecutive subsequences: [1] (sum=1), [2] (sum=2), [4] (sum=4), [1,2] (sum=3). Total = 1+2+4+3 = 10
Example 2 — Decreasing Sequence
$ Input: nums = [3,2]
Output: 8
💡 Note: Consecutive subsequences: [3] (sum=3), [2] (sum=2), [3,2] (sum=5). Total = 3+2+5 = 8
Example 3 — Single Element
$ Input: nums = [5]
Output: 5
💡 Note: Only one subsequence possible: [5] with sum = 5

Constraints

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

Visualization

Tap to expand
Sum of Consecutive Subsequences: [1,2,4]124Input Array+1+2✓ [1] → sum = 1✓ [2] → sum = 2✓ [4] → sum = 4✓ [1,2] → sum = 3 (consecutive)✗ [1,4] → not consecutive✗ [2,4] → not consecutive✗ [1,2,4] → not consecutiveTotal Sum = 1 + 2 + 4 + 3 = 10
Understanding the Visualization
1
Input
Array [1,2,4] - find all consecutive subsequences
2
Process
Identify consecutive patterns (differ by ±1)
3
Output
Sum values: 1+2+4+3 = 10
Key Takeaway
🎯 Key Insight: Use DP to efficiently track consecutive sequences ending at each position rather than checking all 2^n subsequences
Asked in
Google 15 Meta 12 Amazon 8
23.0K Views
Medium Frequency
~35 min Avg. Time
890 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