Compute sum over consecutive-step subarrays
Company: Google
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates proficiency in array processing, detection of consecutive-step arithmetic sequences, and accumulation of subarray sums with attention to large-integer (64-bit) arithmetic.
Constraints
- 1 <= n <= 2 * 10^5
- -10^9 <= a[i] <= 10^9
- Your algorithm must run in O(n) time
- Use 64-bit integer arithmetic for the answer
Examples
Input: []
Expected Output: 0
Explanation: There are no subarrays in an empty array.
Input: [7]
Expected Output: 7
Explanation: The only good subarray is [7], whose value is 7.
Input: [20, 21]
Expected Output: 82
Explanation: Good subarrays are [20], [21], and [20, 21] with values 20, 21, and 41. Total = 82.
Input: [1, 2, 1]
Expected Output: 10
Explanation: Good subarrays are [1], [2], [1], [1,2], and [2,1]. Their values sum to 1 + 2 + 1 + 3 + 3 = 10.
Input: [-2, -1, 0, -1]
Expected Output: -12
Explanation: Good subarrays are the 4 singletons, plus [-2,-1], [-1,0], [-2,-1,0], and [0,-1]. Their values sum to -12.
Input: [1, 2, 2, 1]
Expected Output: 12
Explanation: The equal pair [2,2] breaks both patterns. Good subarrays are the 4 singletons, [1,2], and [2,1]. Total = 12.
Input: [2, 3, 4, 5, 4, 3]
Expected Output: 105
Explanation: There is an increasing run [2,3,4,5] and a decreasing run [5,4,3]. Summing all good subarrays across these runs gives 105.
Hints
- Instead of enumerating all subarrays, count only the good subarrays that end at each index.
- Maintain two DP states: one for subarrays ending at i with step +1, and one for step -1. If the current difference matches, extend every previous subarray in that state.