[LeetCode] Stable Subarrays With Equal Boundary and Interior Sum

3728. Stable Subarrays With Equal Boundary and Interior Sum

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
long long countStableSubarrays(vector<int>& capacity) {
int n = capacity.size();
if (n < 3) return 0;
vector<long long> pre(n+1,0);
for (int i = 0; i < n; ++i) pre[i+1] = pre[i] + capacity[i];
struct PairHash {
size_t operator()(pair<long long,long long> const& p) const noexcept {
return std::hash<long long>()(p.first) ^ (std::hash<long long>()(p.second) << 1);
}
};
unordered_map<pair<long long,long long>, long long, PairHash> mp;
long long ans = 0;
for (int r = 2; r < n; ++r) {
int l = r - 2;
mp[{(long long)capacity[l], pre[l+1]}]++;
pair<long long,long long> target = {(long long)capacity[r], pre[r] - capacity[r]};
auto it = mp.find(target);
if (it != mp.end()) ans += it->second;
}
return ans;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/10/28/PS/LeetCode/stable-subarrays-with-equal-boundary-and-interior-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.