The Count Alternating Subarrays coding problem asks you to find the number of subarrays in a binary array (containing only 0s and 1s) where no two adjacent elements are the same. For example, [0, 1, 0] is alternating, but [0, 1, 1] is not. Every single element is considered an alternating subarray of length 1.
Meta and Capital One use the Count Alternating Subarrays interview question to evaluate your ability to apply a linear scan optimization. It’s a "Medium" problem that tests if you can move beyond O(N^2) (checking every subarray) to O(N) by using the property that an alternating sequence of length L contains L * (L + 1) / 2 alternating subarrays.
This is a Sliding Window / Two Pointers problem, though it can be solved with a simple Linear Scan.
current_length for the current alternating sequence.nums[i] != nums[i-1], increment current_length.nums[i] == nums[i-1], reset current_length to 1.current_length to your total count at each step. This works because adding an element to an alternating sequence of length L creates L+1 new alternating subarrays.nums = [0, 1, 1, 0]
i=0: nums[0]=0. len=1. Total = 1.i=1: nums[1]=1. 1 != 0. len=2. Total = 1 + 2 = 3. (Subarrays: [0], [1], [0,1])i=2: nums[2]=1. 1 == 1. Reset len=1. Total = 3 + 1 = 4. (New subarray: [1])i=3: nums[3]=0. 0 != 1. len=2. Total = 4 + 2 = 6. (New subarrays: [0], [1,0])
Result: 6.This problem is a great example of "Contiguous sequence counting." The pattern "Add current length to total" is also used in problems like "Count Subarrays with Sum K" or "Longest Turbulent Subarray."
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Four Divisors | Medium | Solve | |
| Number of Zero-Filled Subarrays | Medium | Solve | |
| Minimum Moves to Equal Array Elements | Medium | Solve | |
| Adding Two Negabinary Numbers | Medium | Solve | |
| Beautiful Arrangement II | Medium | Solve |