Sum of Consecutive Subarrays - Problem

Imagine you're analyzing number sequences to find patterns! A consecutive subarray is one where each element either increases or decreases by exactly 1 from the previous element.

More formally, an array is consecutive if:

  • arr[i] - arr[i-1] == 1 for all valid indices (ascending), OR
  • arr[i] - arr[i-1] == -1 for all valid indices (descending)

For example:

  • [3, 4, 5] is consecutive (ascending) with sum = 12
  • [9, 8] is consecutive (descending) with sum = 17
  • [7] is consecutive (single element) with sum = 7
  • [3, 4, 3] is NOT consecutive (direction changes)
  • [8, 6] is NOT consecutive (gap of 2)

Goal: Find all consecutive subarrays within the given array and return the sum of their values modulo 109 + 7.

Input & Output

example_1.py โ€” Basic consecutive sequence
$ Input: nums = [1, 2, 3]
โ€บ Output: 20
๐Ÿ’ก Note: All subarrays are consecutive: [1]=1, [1,2]=3, [1,2,3]=6, [2]=2, [2,3]=5, [3]=3. Sum = 1+3+6+2+5+3 = 20
example_2.py โ€” Mixed sequences
$ Input: nums = [1, 3, 2, 4]
โ€บ Output: 16
๐Ÿ’ก Note: Consecutive subarrays: [1]=1, [3]=3, [3,2]=5, [2]=2, [4]=4, single elements plus [3,2]. Sum = 1+3+5+2+4+1 = 16
example_3.py โ€” Single element
$ Input: nums = [5]
โ€บ Output: 5
๐Ÿ’ก Note: Only one subarray [5] with sum 5

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • -109 โ‰ค nums[i] โ‰ค 109
  • Return result modulo 109 + 7

Visualization

Tap to expand
Roller Coaster Track Inspection: Finding Valid Segments345765Segment Analysis:โœ“ Segment [3,4,5]: consecutive ascending (+1 each step)โœ— Gap [5,7]: difference of +2, breaks patternโœ“ Segment [7,6,5]: consecutive descending (-1 each step)Contribution Calculation:Segment [3,4,5]: 3*(1*3) + 4*(2*2) + 5*(3*1) = 9 + 16 + 15 = 40Segment [7,6,5]: 7*(1*3) + 6*(2*2) + 5*(3*1) = 21 + 24 + 15 = 60Total consecutive subarray sum = 100๐ŸŽฏ Key Insight: Find maximal consecutive segments, then calculate contributions mathematically
Understanding the Visualization
1
Identify Patterns
Scan the array to find where consecutive patterns start and end
2
Calculate Contributions
For each element in a consecutive segment, determine how many subarrays it participates in
3
Sum Efficiently
Use mathematical formulas instead of generating all subarrays explicitly
Key Takeaway
๐ŸŽฏ Key Insight: Instead of checking every possible subarray, identify maximal consecutive segments and calculate each element's contribution using the formula (left_positions ร— right_positions), achieving O(n) time complexity.
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
28.4K Views
Medium Frequency
~25 min Avg. Time
856 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