DDSA Solutions

3392. Count Subarrays of Length Three With a Condition

Time: O(n)
Space: O(1)
Advertisement

Intuition

Count subarrays of length 4 with exactly 2 elements satisfying a property. Sliding window of size 4.

Algorithm

  1. 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;
    }
}
Advertisement
Was this solution helpful?