Skip to content

3392. Count Subarrays of Length Three With a Condition 👍

  • Time: $O(n)$
  • Space: $O(1)$
 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] == (nums[i - 1] + nums[i + 1]) * 2)
        ++ans;

    return ans;
  }
};
 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] == (nums[i - 1] + nums[i + 1]) * 2)
        ++ans;

    return ans;
  }
}
1
2
3
4
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:]))