Count Subarrays of Length Three With a Condition solution and explanation
9 more videos on this problem
Count Subarrays of Length Three With a Condition | Easy | Leetcode 3392 | codestorywithMIKcodestorywithMIK · 6:55 · 3K views
3392. Count Subarrays of Length Three With a Condition || Java || Leetcode || HindiCoding Sphere · 5:04 · 596 views
LeetCode 3392 Count Subarrays of Length Three With a Condition | Very Easy | Asked in CognizantCode Harmony · 7:48 · 504 views
Daily Leetcode #1853: Apr 27, 2025 - 3392. Count Subarrays of Length Three With a ConditionProgramming Live with Larry · 4:40 · 390 views
Leetcode 3392. Count Subarrays of Length Three With a Condition | Python Solution | Sliding WindowStatLearn Tech · 4:20 · 172 views
3392. Count Subarrays of Length Three With a Condition (Leetcode Easy)Programming Live with Larry · 2:28 · 147 views
3392. Count Subarrays of Length Three With a Condition | Leetcode Daily - PythonLeetcode Daily · 6:23 · 132 views
3392. Count Subarrays of Length Three With a Condition | Java | Leetcode |JavAttack · 3:55 · 64 views
Leetcode Daily Challenge | 3392. Count Subarrays of Length Three With a Condition | InterviewAbdelrahman Samir · 2:46 · 58 views
3392. Count Subarrays of Length Three With a Condition | Leetcode | C++ | Easy SolutionStack underflow · 1:13 · 28 views
The 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.
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
Approach overview
Problem Overview: You are given an integer array and must count how many subarrays of length 3 satisfy a specific condition. For a subarray [a, b, c], the condition holds when the middle value equals the average of the first and third elements, which can be written as a + c = 2 * b.
Approach 1: Brute Force Enumeration (O(n) time, O(1) space)
The direct way is to examine every contiguous subarray of size three. Iterate from index 0 to n-3, extract the triple (nums[i], nums[i+1], nums[i+2]), and check whether nums[i] + nums[i+2] == 2 * nums[i+1]. Each check is constant time, and there are n-2 such subarrays, so the total time complexity is O(n) with O(1) extra space. This approach is conceptually brute force because it evaluates every possible length‑3 window independently without optimizing further.
Approach 2: Single Pass Sliding Window (O(n) time, O(1) space)
A cleaner implementation treats the problem as a fixed-size sliding window over the array. Move a window of length three across the array using a single loop. For each position i, interpret the window as (nums[i], nums[i+1], nums[i+2]) and check the arithmetic condition nums[i] + nums[i+2] == 2 * nums[i+1]. Because the window size never changes, there is no need for extra data structures—just index access and a simple arithmetic comparison. The traversal touches each element once, giving O(n) time and O(1) space.
This pattern appears frequently in sliding window problems with fixed window sizes. The key observation is the mathematical relationship between the three values. Rewriting the condition as a + c = 2b avoids floating-point averages and keeps the check constant time. The logic also mirrors properties of a three-element arithmetic progression, which connects the problem to simple math reasoning rather than heavier data structures.
Recommended for interviews: The single pass window is what interviewers expect. Start by explaining that only n-2 subarrays of size three exist, then iterate once and check the arithmetic condition. Mentioning the brute force enumeration shows you understand the search space, while implementing the single pass solution demonstrates clean reasoning and optimal O(n) time with constant space.
Solution
We traverse each subarray of length 3 in the array 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 nums. The space complexity is O(1).
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)
)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;
}
}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;
}
};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;
}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
}impl Solution {
pub fn count_subarrays(nums: Vec<i32>) -> i32 {
let mut ans = 0;
for i in 1..nums.len() - 1 {
if (nums[i - 1] + nums[i + 1]) * 2 == nums[i] {
ans += 1;
}
}
ans
}
}Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Enumeration | O(n) | O(1) | Good for understanding the problem by explicitly checking every subarray of length three. |
| Single Pass Sliding Window | O(n) | O(1) | Best practical solution. Uses a fixed window over the array with minimal logic and constant memory. |
Frequently asked questions
Is Count Subarrays of Length Three With a Condition easy or hard?
LeetCode classifies this problem as Easy. The logic only requires scanning the array once and checking a simple arithmetic relationship among three consecutive elements. It mainly tests familiarity with array iteration and recognizing patterns like arithmetic progressions.
Count Subarrays of Length Three With a Condition Python/Java solution
In both Python and Java, iterate through the array from index 0 to n-3 and check whether nums[i] + nums[i+2] == 2 * nums[i+1]. Increment a counter whenever the condition holds. The implementation is short and runs in O(n) time with O(1) space.
How to solve Count Subarrays of Length Three With a Condition in O(n)?
Traverse the array once and evaluate every contiguous triple (nums[i], nums[i+1], nums[i+2]). For each triple, check the condition nums[i] + nums[i+2] == 2 * nums[i+1]. If it holds, increment a counter. This single pass guarantees O(n) time and constant memory usage.
What is the best approach for Count Subarrays of Length Three With a Condition?
The best approach is a single pass sliding window over the array. Iterate from index 0 to n-3 and check whether nums[i] + nums[i+2] equals 2 * nums[i+1]. This verifies that the middle element is the average of its neighbors. The algorithm runs in O(n) time with O(1) extra space.
Is Count Subarrays of Length Three With a Condition asked at Google/Amazon/Meta?
Problems of this style appear frequently in interviews at companies like Amazon, Google, and Meta because they test array traversal and simple mathematical reasoning. While this exact problem may come from LeetCode contests, the pattern of scanning fixed-size windows is very common in interviews.
What data structure is used in Count Subarrays of Length Three With a Condition?
The problem primarily uses a simple array traversal. No advanced data structures are required. A fixed-size sliding window of three elements and basic arithmetic checks are enough to implement the optimal solution.
What is the time complexity of Count Subarrays of Length Three With a Condition?
The optimal solution runs in O(n) time because you examine each possible length‑3 window exactly once. There are n-2 such windows in an array of size n. Each check is constant time, and the algorithm uses O(1) additional space.
