Count Alternating-Parity Subarrays
A contiguous subarray is alternating when every pair of adjacent elements in it has different parity, one odd and one even. A subarray with a single element is alternating.
Given an integer array, return the number of alternating subarrays.
countAlternating([1, 2, 3]) -> 6 // every subarray alternates countAlternating([2, 4, 6]) -> 3 // only the single elements countAlternating([1, 2, 4, 5]) -> 6 // 4 singles, [1,2], [4,5]
Up to 200,000 elements, which may be negative. Enumerating every subarray is too slow.
Hints
Hint 1
Count subarrays by where they end. How many alternating subarrays end at index i?
Hint 2
If the longest alternating stretch ending at i has length L, exactly L alternating subarrays end there. L is one more than the previous L when the parity changes, and one otherwise.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.