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: 2
💡 Note: Check triplets: [1,6,2] → 1+2=3, 6/2=3 ✓. [6,2,4] → 6+4=10, 2/2=1 ✗. [2,4,8] → 2+8=10, 4/2=2 ✗. [4,8,2] → 4+2=6, 8/2=4 ✗. Two valid triplets.

Constraints

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

Visualization

Tap to expand
Count Subarrays: Check condition for each triplet2103184Triplet [2,10,3]2 + 3 = 5, 10÷2 = 5 ✓Triplet [10,3,1]10 + 1 = 11, 3÷2 = 1.5 ✗Continue checking all possible triplets...Valid Count: 1Only one triplet satisfies: first + third = middle ÷ 2
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