FastPrepCount Uniform-or-Alternating Parity Subarrays

Count Uniform-or-Alternating Parity Subarrays

Visa logoVisa● MediumINTERNOA
Learn

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[]) → long

Examples

Example 1

nums = [1,2,3,4]return = 10

The entire array alternates, so every one of its 4 * 5 / 2 = 10 subarrays is valid.

Example 2

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

All values are odd, so every subarray has uniform parity.

Example 3

nums = [1,2,4]return = 5

All 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.

More Visa problems

See Visa hiring insights
public long countUniformOrAlternatingParitySubarrays(int[] nums) {
    // Write your code here.
}
nums[1,2,3,4]
expected10
Checking account…