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 INPUT Array nums: 1 idx 0 2 idx 1 4 idx 2 Consecutive Subsequences: [1] = 1 [2] = 2 [4] = 4 [1,2] = 3 [2,4] X (gap=2) [1,4] X (gap=3) Only diff=1 or diff=-1 allowed nums = [1, 2, 4] ALGORITHM (DP) 1 Track Increasing dp_inc[v] = count ending at v 2 Track Decreasing dp_dec[v] = count ending at v 3 Sum Contributions Each element adds to total 4 Apply Modulo Result mod 10^9 + 7 Calculation: [1]: 1 [2]: 2 [4]: 4 [1,2]: 1+2 = 3 Total: 1+2+4+3 = 10 FINAL RESULT All Valid Subsequences: [1] [2] [4] [1,2] Sum of values: 1 + 2 + 4 + 3 Output: 10 OK - Verified Key Insight: Use two DP maps: one for increasing subsequences (diff=+1) and one for decreasing (diff=-1). For each element v, check dp[v-1] and dp[v+1] to extend existing sequences. Track sum contributions as you go, multiplying each element by how many subsequences it appears in. TutorialsPoint - Sum of Consecutive Subsequences | DP Approach
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