Count Subarrays of Length Three With a Condition Problem
#3392
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3392.
Given an integer array nums, return the number of subarrays of length 3 such that the sum of the first and third numbers equals exactly half of the second number.
Example 1:
Input: nums = [1,2,1,4,1]
Output: 1
Explanation:
Only the subarray [1,4,1] contains exactly 3 elements where the sum of the first and third numbers equals half the middle number.
Example 2:
Input: nums = [1,1,1]
Output: 0
Explanation:
[1,1,1] is the only subarray of length 3. However, its first and third numbers do not add to half the middle number.
Constraints:
3 <= nums.length <= 100-100 <= nums[i] <= 100
Solution
Approach: Single Pass
Look at each window of three consecutive numbers and check whether twice the sum of the first and third equals the middle number. Count the windows that do.
Complexity: Time O(n), space O(1).
class Solution:
def countSubarrays(self, nums: List[int]) -> int:
return sum(
(nums[i - 1] + nums[i + 1]) * 2 == nums[i] for i in range(1, len(nums) - 1)
)