3392. Count Subarrays of Length Three With a Condition
MediumView on LeetCode
Time: O(n)
Space: O(1)
Problem Overview
Count subarrays of length 4 with exactly 2 elements satisfying a property.
Intuition
Count subarrays of length 4 with exactly 2 elements satisfying a property. Sliding window of size 4.
Algorithm
- 1Sliding window of size exactly 4. Count elements satisfying condition. Count windows with exactly 2.
Common Pitfalls
- •Fixed window size 4. Slide across array, count qualifying windows.
3392.cs
C#
// Approach: Scan all length-3 windows; check if middle == (left + right) / 2.
// Time: O(n) Space: O(1)
public 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;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)
- 27. Remove Element(Easy)