Skip to content

3392. Count Subarrays of Length Three With a Condition

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 non-empty sequence of elements within an array.

Example 1:

Input: nums = [1,2,1,4,1]

Output: 1

Explanation:

Only the subarray [1,4,1] contains exactly 3 elements where the sum of the first and third numbers equals half the middle number.

Example 2:

Input: nums = [1,1,1]

Output: 0

Explanation:

[1,1,1] is the only subarray of length 3. However, its first and third numbers do not add to half the middle number.

Constraints:

  • 3 <= nums.length <= 100
  • -100 <= nums[i] <= 100

Solution:

class Solution {
    public int countSubarrays(int[] nums) {
        int result = 0;
        for (int i = 2; i < nums.length; i++){
            if ((nums[i -2] + nums[i]) * 2 == nums[i - 1]){
                result++;
            }
        }

        return result;
    }
}
// TC: O(n)
// SC: O(1)
class Solution {
    public int countSubarrays(int[] nums) {
        // return the number of subarrays 
        // length 3 such that the sum of the first
        // third
        // sliding window
        int result = 0;
        int n = nums.length;

        if (n < 3){
            return 0;
        }
        // 0 1  2   3
       // [-1,-4,-1,4]
       //     l  
        //          r
        //

        int left = 0;
        int right = 2;
        while(right < n){ // 4
            if ((nums[right] + nums[left])*2 == nums[right - 1] ){
                result++; // 
            }

            right++;
            left++;
        }


        if (right == 2){
            if ((nums[right] + nums[left])* 2 == nums[right - 1]){
                result++;
            }
        }

        return result;
    }
}

// TC: O(n)
// SC: O(1)

1+ 2 = 1/2

(a + c) = b/2

b % 2 == 0 && (a+c)=b /2