Count Subarrays of Length Three With a Condition - Problem

Given an integer array nums, return the number of subarrays of length 3 such that the sum of the first and third numbers equals exactly half of the second number.

A subarray is a contiguous part of an array. For each valid subarray [nums[i], nums[i+1], nums[i+2]], check if nums[i] + nums[i+2] == nums[i+1] / 2.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4,5]
Output: 0
💡 Note: Check each triplet: [1,2,3] → 1+3=4, 2/2=1, 4≠1. [2,3,4] → 2+4=6, 3/2=1.5, 6≠1.5. [3,4,5] → 3+5=8, 4/2=2, 8≠2. No valid triplets.
Example 2 — Valid Triplet
$ Input: nums = [2,10,3]
Output: 1
💡 Note: Triplet [2,10,3]: 2+3=5, 10/2=5. Since 5=5, this triplet satisfies the condition. Count = 1.
Example 3 — Multiple Triplets
$ Input: nums = [1,6,2,4,8,2]
Output: 1
💡 Note: Check triplets: [1,6,2] → 2*(1+2)=6, middle=6 ✓. [6,2,4] → 2*(6+4)=20, middle=2 ✗. [2,4,8] → 2*(2+8)=20, middle=4 ✗. [4,8,2] → 2*(4+2)=12, middle=8 ✗. One valid triplet.

Constraints

  • 3 ≤ nums.length ≤ 100
  • -100 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Count Subarrays of Length Three With a Condition INPUT nums = [1, 2, 3, 4, 5] 1 2 3 4 5 i=0 i=1 i=2 i=3 i=4 Condition to Check: nums[i] + nums[i+2] == nums[i+1] / 2 Subarrays of Length 3: [1, 2, 3] [2, 3, 4] [3, 4, 5] 3 subarrays to evaluate ALGORITHM STEPS 1 Check [1,2,3] 1+3=4, 2/2=1 4 != 1 (NO) 2 Check [2,3,4] 2+4=6, 3/2=1.5 6 != 1.5 (NO) 3 Check [3,4,5] 3+5=8, 4/2=2 8 != 2 (NO) 4 Count Valid No matches found count = 0 Mathematical Check: first + third == middle / 2 Or equivalently: 2*(first + third) == middle FINAL RESULT Output: 0 No Valid Subarrays Found Summary: [1,2,3]: 1+3=4 4 != 1 [2,3,4]: 2+4=6 6 != 1.5 [3,4,5]: 3+5=8 8 != 2 Total Valid: 0 Result Confirmed: OK Time: O(n), Space: O(1) Key Insight: The condition nums[i] + nums[i+2] == nums[i+1] / 2 requires the middle element to be exactly twice the sum of first and third elements. This is a rare condition that limits valid subarrays. Mathematical Optimization: Use 2*(first + third) == middle to avoid floating point issues. TutorialsPoint - Count Subarrays of Length Three With a Condition | Mathematical Optimization Approach
Asked in
Google 25 Amazon 15
12.5K Views
Medium Frequency
~15 min Avg. Time
234 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