FastPrepCount Alternating-Parity Subarrays

Count Alternating-Parity Subarrays

Visa logoVisa● EasyFULLTIMEOA
Learn

Problem statement

You are given an integer array nums.

A contiguous subarray is alternating when every pair of adjacent elements has different parity: one is even and the other is odd. Every one-element subarray is alternating.

Return the total number of alternating contiguous subarrays.

Function

countAlternatingParitySubarrays(nums: int[]) → long

Examples

Example 1

nums = [1,3,5,7,9]return = 5

Every adjacent pair has odd-odd parity, so only the five one-element subarrays qualify.

Example 2

nums = [1,2,1,2,1]return = 15

The entire array alternates. All 5 * 6 / 2 = 15 contiguous subarrays therefore qualify.

Example 3

nums = [1,2,3,7,6,5]return = 12

The equal-parity pair 3, 7 splits the array into two alternating runs of length 3. Each contributes 3 * 4 / 2 = 6 subarrays.

Constraints

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109
  • The answer fits in a signed 64-bit integer.

More Visa problems

See Visa hiring insights
public long countAlternatingParitySubarrays(int[] nums) {
    // Write your code here.
}
nums[1,3,5,7,9]
expected5
Checking account…