Problem Description
Given an integer array nums, return the number of contiguous subarrays of length 3 such that the sum of the first and third numbers equals exactly half of the middle number.
Key Insights
- Iterate through the array considering every contiguous subarray of length 3.
- For each subarray [a, b, c], check if b is even; if not, the condition cannot be met exactly.
- If b is even, verify whether a + c equals b/2.
- Use a simple loop to count the subarrays that satisfy the condition.
Space and Time Complexity
Time Complexity: O(n) - We make a single pass through the array. Space Complexity: O(1) - We use a few extra variables and no additional data structures.
Solution
We use a sliding window approach by iterating through the array from index 0 to n-3. For each index, we extract the triplet [nums[i], nums[i+1], nums[i+2]]. The middle element must be even because only then can half of it be an integer. If even, we compute half of the middle element and check if the sum of the first and third elements equals this value. Each valid subarray increments our counter. This method efficiently solves the problem in a single pass using constant space.