Skip to main content
impol.dev

Editorial

Solution walkthrough

Review the explanation, then compare the reference implementation.

Video explanation

Solution

Intuition

Every candidate has exactly three consecutive elements, so only its ending index needs enumeration. The first and third values must sum to half the middle value. Since their sum is an integer, an odd middle value cannot satisfy the condition.

Approach

Scan ending indices from two through the end of the array. For each triple, first check that its middle value is even. If so, compare the sum of the two endpoints with half the middle value and increment the count when they are equal.

Return the total. Each length-three subarray has one unique ending index, so it is checked exactly once. The parity check and arithmetic comparison work for negative and zero values as well as positive ones; no positivity assumption is needed.

class Solution: def countSubarrays(self, nums: List[int]) -> int: n = len(nums) res = 0 for i in range(2, n): if nums[i - 1] % 2 == 0 and (nums[i - 2] + nums[i]) == nums[i - 1] / 2: res += 1 return res

Complexity analysis

Let n = nums.length. Time: O(n). Auxiliary space: O(1).