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 INPUT Binary Array nums[] 0 i=0 1 i=1 0 i=2 1 i=3 All alternating! Input Values nums = [0, 1, 0, 1] Length n = 4 Alternating = Adjacent differ [0,1] OK [1,0] OK [0,1,0] OK [1,0,1] OK [0,1,0,1] OK ALGORITHM STEPS 1 Initialize count = 0, length = 1 2 Iterate Array Compare nums[i] with nums[i-1] 3 Update Window If different: length++ If same: length = 1 4 Add to Count count += length each step Window Trace i=0: len=1, count=1 i=1: 1!=0, len=2, count=1+2=3 i=2: 0!=1, len=3, count=3+3=6 i=3: 1!=0, len=4, count=6+4=10 Total = 10 FINAL RESULT All Alternating Subarrays: Length 1: [0] [1] [0] [1] = 4 Length 2: [0,1] [1,0] [0,1] = 3 Length 3: [0,1,0] [1,0,1] = 2 Length 4: [0,1,0,1] = 1 Total: 4 + 3 + 2 + 1 = 10 OUTPUT 10 OK - Verified! Formula for full alternating: n*(n+1)/2 = 4*5/2 = 10 Key Insight: The sliding window optimization tracks the length of the current alternating sequence. Each position contributes 'length' new subarrays ending at that index. This avoids counting all subarrays explicitly, achieving O(n) time complexity instead of O(n^2). TutorialsPoint - Count Alternating Subarrays | Sliding Window Optimization
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