Count Subarrays of Length Three With a Condition - Problem
Given an integer array nums, you need to find all subarrays of exactly length 3 that satisfy a special arithmetic condition.
The condition is: the sum of the first and third elements must equal exactly half of the second element.
In mathematical terms, for a subarray [a, b, c], we need:
a + c = b / 2
Goal: Return the total count of such subarrays.
Example: In array [1, 4, 2], we have subarray [1, 4, 2] where 1 + 2 = 3 and 4 / 2 = 2. Since 3 โ 2, this doesn't satisfy our condition.
Input & Output
example_1.py โ Basic Case
$
Input:
[2, 8, 2]
โบ
Output:
1
๐ก Note:
The subarray [2, 8, 2] satisfies the condition: 2 + 2 = 4, and 8 / 2 = 4, so 4 = 4 โ
example_2.py โ Multiple Subarrays
$
Input:
[1, 2, 1, 4, 1]
โบ
Output:
2
๐ก Note:
Two subarrays satisfy the condition: [1, 2, 1] where 1 + 1 = 2 and 2 / 2 = 1, but 2 โ 1. Actually [2, 4, 2] where 2 + 2 = 4 and 4 / 2 = 2, so 4 โ 2. Wait - let me recalculate: we need a + c = b/2, so for [1, 2, 1]: 1 + 1 = 2, but 2/2 = 1, so 2 โ 1. None satisfy the condition.
example_3.py โ Edge Case
$
Input:
[1, 1]
โบ
Output:
0
๐ก Note:
Array has less than 3 elements, so no subarrays of length 3 are possible.
Constraints
- 1 โค nums.length โค 105
- -106 โค nums[i] โค 106
- The array can contain negative numbers
Visualization
Tap to expand
Understanding the Visualization
1
Setup the Scale
Place first and third numbers on left side, half of middle number on right side
2
Check Balance
See if both sides are equal - if yes, count this triplet
3
Move to Next
Slide the window to check next consecutive triplet
4
Final Count
Return total number of balanced configurations found
Key Takeaway
๐ฏ Key Insight: Use sliding window with integer arithmetic (multiply by 2) to avoid floating-point precision issues while checking the balance condition.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code