Count Alternating Subarrays - Problem
Given a binary array nums containing only 0s and 1s, your task is to count the number of alternating subarrays.
An alternating subarray is a contiguous subsequence where no two adjacent elements have the same value. In other words, the values must alternate between 0 and 1 throughout the subarray.
Examples of alternating patterns:
[0, 1]✅ alternating[1, 0, 1]✅ alternating[0, 0]❌ not alternating[1, 1, 0]❌ not alternating
Return the total count of all possible alternating subarrays in the given array.
Note: Single elements are always considered alternating subarrays.
Input & Output
example_1.py — Basic alternating pattern
$
Input:
nums = [0, 1, 1, 1]
›
Output:
5
💡 Note:
The alternating subarrays are: [0], [1], [1], [1], [0,1]. Note that subarrays like [1,1] are not alternating since adjacent elements are the same.
example_2.py — Perfect alternating sequence
$
Input:
nums = [1, 0, 1, 0]
›
Output:
10
💡 Note:
All possible subarrays are alternating: [1], [0], [1], [0], [1,0], [0,1], [1,0], [1,0,1], [0,1,0], [1,0,1,0]. Total count = 10.
example_3.py — Single element array
$
Input:
nums = [1]
›
Output:
1
💡 Note:
Only one subarray exists: [1], which is considered alternating by definition.
Constraints
- 1 ≤ nums.length ≤ 105
- nums[i] is either 0 or 1
- The array contains only binary values
Visualization
Tap to expand
Understanding the Visualization
1
Identify Sequences
Find all maximal alternating sequences (like finding stretches of properly alternating traffic lights)
2
Apply Math Formula
For each sequence of length L, calculate L×(L+1)/2 total subarrays
3
Sum All Counts
Add up counts from all alternating sequences to get the final answer
Key Takeaway
🎯 Key Insight: By recognizing that each alternating sequence of length L contains exactly L×(L+1)/2 subarrays, we can solve this problem in linear time rather than cubic time.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code