Skip to main content
Back to problems
#3101
Medium Algorithms

Count alternating subarrays

Array Math
57.3% acceptance
Feb 23, 2026
242
10
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn count_alternating_subarrays(nums: Vec<i32>) -> i64 {
    let mut result: i64 = 1;
    let mut run: i64 = 1;
    for i in 1..nums.len() {
      if nums[i] != nums[i - 1] {
        run += 1;
      } else {
        run = 1;
      }
      result += run;
    }
    result
  }
}