Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created April 27, 2025 22:30
Show Gist options
  • Save Ifihan/a9cd419340ef262ba412d8d361927f35 to your computer and use it in GitHub Desktop.
Save Ifihan/a9cd419340ef262ba412d8d361927f35 to your computer and use it in GitHub Desktop.
Count Subarrays of Length Three With a Condition

Question

Approach

When solving this, I noticed that I only needed to check all subarrays of length 3. So I iterated over the array, looking at every group of three consecutive numbers. For each triplet, I checked if the sum of the first and third numbers was exactly half of the second number. If the condition was satisfied, I incremented my answer counter.

Implementation

class Solution:
    def countSubarrays(self, nums: List[int]) -> int:
        count = 0
        n = len(nums)
        
        for i in range(n - 2):
            if nums[i] + nums[i + 2] == nums[i + 1] / 2:
                count += 1
        
        return count

Complexities

  • Time: O(n)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment