Problem Statement in English
You’re given an integer array nums of length. Your task is to find the number of subarrays of length 3 such that the sum of their first and last element is equal to the sum of the middle element.
Approach
This is a straightforward sliding window problem.
Solution in Python
class Solution:
def countSubarrays(self, nums: List[int]) -> int:
res = l = 0
s = sum(nums[:2])
for r in range(2, len(nums)):
s += nums[r]
if not (nums[l + 1] % 2) and s - nums[l+1] == nums[l + 1] // 2:
res += 1
s -= nums[l]
l += 1
return res
Complexity
Time: $O(n)$
Since we iterate over the array once.Space: $O(1)$
Since we only use a few variables to store the result and the current sum, the space complexity is constant.
And we are done.