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
🚦 Traffic Light Sequence CounterGRGGRSequence 1: Length 3Sequence 2: Length 2Mathematical Formula: L × (L + 1) ÷ 2Sequence 1 (L=3): 3 × 4 ÷ 2 = 6 valid subsequences• [G], [R], [G], [G-R], [R-G], [G-R-G]Sequence 2 (L=2): 2 × 3 ÷ 2 = 3 valid subsequences• [G], [R], [G-R]Total: 6 + 3 = 9 alternating subsequences⚡ Key InsightInstead of checking every possible subsequence (O(n³)), we findalternating segments once and use math to count efficiently (O(n))
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.
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
42.4K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen