Count Uniform-or-Alternating Parity Subarrays
Problem statement
You are given an integer array nums.
A contiguous subarray is valid when its parity pattern is one of:
- uniform: every value has the same parity, or
- alternating: every adjacent pair has different parity.
Every one-element and two-element subarray is valid. Return the total number of valid contiguous subarrays.
Function
countUniformOrAlternatingParitySubarrays(nums: int[]) → longExamples
Example 1
nums = [1,2,3,4]return = 10The entire array alternates, so every one of its 4 * 5 / 2 = 10 subarrays is valid.
Example 2
nums = [1,3,5,7]return = 10All values are odd, so every subarray has uniform parity.
Example 3
nums = [1,2,4]return = 5All three singletons and both length-two subarrays are valid. The full parity pattern odd-even-even is neither uniform nor alternating.
Constraints
1 <= nums.length <= 105-109 <= nums[i] <= 109- The answer fits in a signed 64-bit integer.