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
Count Alternating Subarrays: [0,1,0,1]0101✓ Adjacent elements are differentLength 1: 4 subarraysLength 2: 3 subarraysLength 3: 2 subarraysLength 4: 1 subarrayTotal: 4 + 3 + 2 + 1 = 10Formula: n*(n+1)/2 where n = segment lengthFor length 4: 4*5/2 = 10 alternating subarrays
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
Asked in
Google 25 Amazon 20 Microsoft 15
25.0K Views
Medium Frequency
~15 min Avg. Time
890 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