Skip to content

← leetcode

Count Subarrays of Length Three With a Condition

· Easy

LeetCode problem 3392

Unfortunately this question is quite straightforward; optimal solution is just a for-loop iterating through every contiguous triplet.

code

class Solution {
public:
    int countSubarrays(vector<int>& nums) {
        int ans = 0;
        for (int i = 0; i < nums.size()-2; ++i) {
            if (2*(nums[i] + nums[i+2]) == nums[i+1]) {
                ++ans;
            }
        }
        return ans;
    }
};

complexity

  • Time: O(n) where n is the length of the array nums
  • Space: O(1)

time taken

  • 1 minutes and 37 seconds