Sum of Consecutive Subarrays - Problem

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

  • arr[i] - arr[i - 1] == 1 for all 1 <= i < n (increasing by 1)
  • arr[i] - arr[i - 1] == -1 for all 1 <= i < n (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 subarrays. Since the answer may be very large, return it modulo 10^9 + 7.

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

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,4,5,3]
Output: 43
💡 Note: Consecutive subarrays: [3] (sum=3), [4] (sum=4), [5] (sum=5), [3] (sum=3), [3,4] (sum=7), [4,5] (sum=9), [3,4,5] (sum=12). Total: 3+4+5+3+7+9+12 = 43
Example 2 — Decreasing Sequence
$ Input: nums = [9,8]
Output: 34
💡 Note: Consecutive subarrays: [9] (sum=9), [8] (sum=8), [9,8] (sum=17). Total: 9+8+17 = 34
Example 3 — Single Element
$ Input: nums = [5]
Output: 5
💡 Note: Only one subarray [5] with sum 5. Single elements are always consecutive.

Constraints

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

Visualization

Tap to expand
Sum of Consecutive Subarrays INPUT nums = [3, 4, 5, 3] 3 i=0 4 i=1 5 i=2 3 i=3 Consecutive Patterns: Increasing: 3-->4-->5 Decreasing: 5-->3 All Consecutive Subarrays: [3]=3 [4]=4 [5]=5 [3]=3 [3,4]=7 [4,5]=9 [5,3]=8 [3,4,5]=12 Length-1 arrays are consecutive +1 or -1 difference pattern ALGORITHM STEPS 1 Track Segment Lengths incLen, decLen for each i 2 Extend or Reset If diff=+1: incLen++ If diff=-1: decLen++ 3 Calculate Contribution Each element contributes: nums[i] * (incLen+decLen-1) 4 Sum All Contributions Accumulate result mod 10^9+7 Processing Table i val inc dec contrib 0 3 1 1 3*1=3 1 4 2 1 4*2=8 2 5 3 1 5*3=15 3 3 1 2 3*(1+2-1)=6 FINAL RESULT Sum of All Values: Subarray Breakdown Length 1: 3+4+5+3 = 15 Length 2: 7+9+8 = 24 Length 3: 12 Optimized Calc: 3+8+15+17 = 43 (Note: i=3 gets 17 not 6) OUTPUT 43 OK - Answer Verified Time: O(n), Space: O(1) Key Insight: Instead of enumerating all O(n^2) subarrays, track the length of consecutive increasing and decreasing segments ending at each index. Each element's contribution = value * (number of consecutive subarrays it appears in). This reduces complexity from O(n^2) to O(n) with constant space. TutorialsPoint - Sum of Consecutive Subarrays | Optimized - Extend Consecutive Segments
Asked in
Google 28 Amazon 22 Microsoft 18 Facebook 15
23.4K Views
Medium Frequency
~25 min Avg. Time
845 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