Skip to content

3392. Count Subarrays of Length Three With a Condition

Description

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

Solutions

Solution 1: Single Pass

We traverse each subarray of length $3$ in the array $\textit{nums}$ and check if twice the sum of the first and third numbers equals the second number. If it does, we increment the answer by $1$.

After traversing, we return the answer.

The time complexity is $O(n)$, where $n$ is the length of the array $\textit{nums}$. The space complexity is $O(1)$.

1
2
3
4
5
class Solution:
    def countSubarrays(self, nums: List[int]) -> int:
        return sum(
            (nums[i - 1] + nums[i + 1]) * 2 == nums[i] for i in range(1, len(nums) - 1)
        )
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
    public int countSubarrays(int[] nums) {
        int ans = 0;
        for (int i = 1; i + 1 < nums.length; ++i) {
            if ((nums[i - 1] + nums[i + 1]) * 2 == nums[i]) {
                ++ans;
            }
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
public:
    int countSubarrays(vector<int>& nums) {
        int ans = 0;
        for (int i = 1; i + 1 < nums.size(); ++i) {
            if ((nums[i - 1] + nums[i + 1]) * 2 == nums[i]) {
                ++ans;
            }
        }
        return ans;
    }
};
1
2
3
4
5
6
7
8
func countSubarrays(nums []int) (ans int) {
    for i := 1; i+1 < len(nums); i++ {
        if (nums[i-1]+nums[i+1])*2 == nums[i] {
            ans++
        }
    }
    return
}
1
2
3
4
5
6
7
8
9
function countSubarrays(nums: number[]): number {
    let ans: number = 0;
    for (let i = 1; i + 1 < nums.length; ++i) {
        if ((nums[i - 1] + nums[i + 1]) * 2 === nums[i]) {
            ++ans;
        }
    }
    return ans;
}

Comments