Skip to main content
Back to problems
#3392
Easy Algorithms

Count subarrays of length three with a condition

Array
61.5% acceptance
Feb 24, 2026
301
31
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn count_subarrays(nums: Vec<i32>) -> i32 {
    let n = nums.len();
    let mut ans = 0;
    for i in 0..n-2 {
      // (nums[i] + nums[i+2]) == nums[i+1] / 2
      // Multiply by 2 to avoid fractions: 2*(nums[i] + nums[i+2]) == nums[i+1]
      if 2 * (nums[i] + nums[i+2]) == nums[i+1] {
        ans += 1;
      }
    }
    ans
  }
}