Given an integer array nums, find the count of sub-arrays of size 3 where the sum of the first and third elements equals the second element.
In other words, for each contiguous sub-array [nums[i], nums[i+1], nums[i+2]], count it if nums[i] + nums[i+2] == nums[i+1].
Function Signature
def count_subarrays(nums: list[int]) -> int:
Rules
-
Sub-arrays are contiguous. Windows that overlap are counted separately, so one element can belong to several qualifying windows.
-
Values can be negative or zero.
Constraints
-
3 <= len(nums) <= 10^5
-
-10^4 <= nums[i] <= 10^4
Examples
Input: nums = [1,4,3,2,5,1]
Output: 1
The windows are [1,4,3], [4,3,2], [3,2,5] and [2,5,1]. Only [1,4,3] qualifies, since 1 + 3 = 4; the other three give 6, 8 and 3 against middle values 3, 2 and 5.
Input: nums = [1,2,1,4,2,2]
Output: 1
Only [1,2,1] qualifies, since 1 + 1 = 2. The windows [2,1,4], [1,4,2] and [4,2,2] give 6, 3 and 6 against middle values 1, 4 and 2.
Input: nums = [-1,1,2,1,-1]
Output: 3
All three windows qualify: -1 + 2 = 1, 1 + 1 = 2 and 2 + (-1) = 1. They overlap, and each one counts.