When solving this, I noticed that I only needed to check all subarrays of length 3. So I iterated over the array, looking at every group of three consecutive numbers. For each triplet, I checked if the sum of the first and third numbers was exactly half of the second number. If the condition was satisfied, I incremented my answer counter.
class Solution:
def countSubarrays(self, nums: List[int]) -> int:
count = 0
n = len(nums)
for i in range(n - 2):
if nums[i] + nums[i + 2] == nums[i + 1] / 2:
count += 1
return count
- Time: O(n)
- Space: O(1)
