4083. Stable Subarrays With Equal Boundary and Interior Sum
My accepted Python solution to LeetCode problem 4083, Stable Subarrays With Equal Boundary and Interior Sum, running in 387ms.
- Difficulty: Medium
- Python
- Runtime 387ms
- Memory 59.1MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 387ms, memory 59.1MB, accepted 2025-12-30.
class Solution:
def countStableSubarrays(self, capacity: List[int]) -> int:
n = len(capacity)
count = 0
prefix = [0] * (n + 1)
for i in range(n):
prefix[i + 1] = prefix[i] + capacity[i]
from collections import defaultdict
seen = defaultdict(int)
for r in range(2, n): # r starts from 2 (minimum length 3)
# Add l = r - 2 first (so it can be matched)
l = r - 2
seen[(capacity[l], prefix[l])] += 1
# Then check for matches
target = prefix[r] - 2 * capacity[r]
count += seen[(capacity[r], target)]
return count