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] == 1for all valid indices (ascending), ORarr[i] - arr[i-1] == -1for 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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code