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
224First + ThirdSecond รท 2Balanced! 2 + 2 = 4
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.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.4K Views
Medium Frequency
~12 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen