Stable Subarrays With Equal Boundary and Interior Sum Problem
Description
LeetCode Problem 3728.
You are given an integer array capacity.
A subarray capacity[l..r] is considered stable if:
- Its length is at least 3.
- The first and last elements are each equal to the sum of all elements strictly between them (i.e.,
capacity[l] = capacity[r] = capacity[l + 1] + capacity[l + 2] + ... + capacity[r - 1]).
Return an integer denoting the number of stable subarrays.
Example 1:
Input: capacity = [9,3,3,3,9]
Output: 2
Explanation:
- [9,3,3,3,9] is stable because the first and last elements are both 9, and the sum of the elements strictly between them is 3 + 3 + 3 = 9.
- [3,3,3] is stable because the first and last elements are both 3, and the sum of the elements strictly between them is 3.
Example 2:
Input: capacity = [1,2,3,4,5]
Output: 0
Explanation:
No subarray of length at least 3 has equal first and last elements, so the answer is 0.
Example 3:
Input: capacity = [-4,4,0,0,-8,-4]
Output: 1
Explanation:
[-4,4,0,0,-8,-4] is stable because the first and last elements are both -4, and the sum of the elements strictly between them is 4 + 0 + 0 + (-8) = -4
Constraints:
3 <= capacity.length <= 10^5-10^9 <= capacity[i] <= 10^9
Solution
Approach: Prefix Sum + Hash Table
Let s[i] be the sum of the first i elements. A subarray capacity[l..r] is stable when
capacity[l] = capacity[r] = s[r] - s[l + 1].
Enumerate the right end r. The left end l must satisfy l <= r - 2, so when we reach r we insert the newly allowed left end l = r - 2 into a hash table cnt. The key of a left end is the pair (capacity[l], capacity[l] + s[l + 1]): its first value is the required boundary, and the second is the prefix sum s[r] that makes the interior sum equal to it.
For the current r, the number of valid left ends is the count stored under the key (capacity[r], s[r]); add it to the answer.
Complexity: time O(n), space O(n). Prefix sums can reach about 10^14, so use 64-bit integers.
from collections import defaultdict
from itertools import accumulate
class Solution:
def countStableSubarrays(self, capacity: List[int]) -> int:
s = list(accumulate(capacity, initial=0))
n = len(capacity)
ans = 0
cnt = defaultdict(int)
for r in range(2, n):
l = r - 2
cnt[(capacity[l], capacity[l] + s[l + 1])] += 1
ans += cnt[(capacity[r], s[r])]
return ans