Count Alternating Subarrays Problem
#3101
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 3101.
You are given a binary array nums.
We call a subarray alternating if no two adjacent elements in the subarray have the same value.
Return the number of alternating subarrays in nums.
Example 1:
Input: nums = [0,1,1,1]
Output: 5
Explanation:
The following subarrays are alternating: [0], [1], [1], [1], and [0,1].
Example 2:
Input: nums = [1,0,1,0]
Output: 10
Explanation:
Every subarray of the array is alternating. There are 10 possible subarrays that we can choose.
Constraints:
1 <= nums.length <= 10^5nums[i]is either0or1.
Solution
Approach: Count Subarrays by Right End
Let s be the number of alternating subarrays ending at the current index. If nums[i] differs from nums[i - 1], every such subarray ending at i - 1 extends, plus the single element, so s = s + 1. Otherwise s resets to 1. The answer is the sum of s over all indices.
Complexity: O(n) time and O(1) space.
class Solution:
def countAlternatingSubarrays(self, nums: List[int]) -> int:
ans = s = 1
for i in range(1, len(nums)):
s = s + 1 if nums[i] != nums[i - 1] else 1
ans += s
return ans