3392. Count Subarrays of Length Three With a Condition LeetCode Solution
In this guide, you will get 3392. Count Subarrays of Length Three With a Condition LeetCode Solution with the best time and space complexity. The solution to Count Subarrays of Length Three With a Condition problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Count Subarrays of Length Three With a Condition solution in C++
- Count Subarrays of Length Three With a Condition solution in Java
- Count Subarrays of Length Three With a Condition solution in Python
- Additional Resources

Problem Statement of 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.
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
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
3392. Count Subarrays of Length Three With a Condition LeetCode Solution in C++
class Solution {
public:
int countSubarrays(vector<int>& nums) {
int ans = 0;
for (int i = 1; i + 1 < nums.size(); ++i)
if (nums[i] == (nums[i - 1] + nums[i + 1]) * 2)
++ans;
return ans;
}
};
/* code provided by PROGIEZ */
3392. Count Subarrays of Length Three With a Condition LeetCode Solution in Java
class Solution {
public int countSubarrays(int[] nums) {
int ans = 0;
for (int i = 1; i + 1 < nums.length; ++i)
if (nums[i] == (nums[i - 1] + nums[i + 1]) * 2)
++ans;
return ans;
}
}
// code provided by PROGIEZ
3392. Count Subarrays of Length Three With a Condition LeetCode Solution in Python
class Solution:
def countSubarrays(self, nums: list[int]) -> int:
return sum(b == (a + c) * 2
for a, b, c in zip(nums, nums[1:], nums[2:]))
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.