Count Alternating Subarrays - Problem
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.
A subarray is a contiguous non-empty sequence of elements within an array.
Input & Output
Example 1 — Fully Alternating
$
Input:
nums = [0,1,0,1]
›
Output:
10
💡 Note:
All subarrays are alternating: [0], [1], [0], [1], [0,1], [1,0], [0,1], [0,1,0], [1,0,1], [0,1,0,1]. Total = 10.
Example 2 — Mixed Pattern
$
Input:
nums = [0,1,1,0]
›
Output:
5
💡 Note:
Alternating subarrays: [0], [1], [1], [0], [0,1]. The segment [1,1] breaks alternation, so [0,1,1] and longer are not valid.
Example 3 — All Same
$
Input:
nums = [1,1,1]
›
Output:
3
💡 Note:
Only single-element subarrays are alternating: [1], [1], [1]. No multi-element alternating subarrays exist.
Constraints
- 1 ≤ nums.length ≤ 105
- nums[i] is either 0 or 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Binary array with 0s and 1s
2
Process
Find all subarrays with no adjacent equal elements
3
Output
Total count of valid alternating subarrays
Key Takeaway
🎯 Key Insight: Each alternating segment of length n contributes exactly n*(n+1)/2 subarrays to the total count
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code