3101. Count Alternating Subarrays LeetCode Solution
In this guide, you will get 3101. Count Alternating Subarrays LeetCode Solution with the best time and space complexity. The solution to Count Alternating Subarrays problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Count Alternating Subarrays solution in C++
- Count Alternating Subarrays solution in Java
- Count Alternating Subarrays solution in Python
- Additional Resources

Problem Statement of Count Alternating Subarrays
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.
Example 1:
Input: nums = [0,1,1,1]
Output: 5
Explanation:
The following subarrays are alternating: [0], [1], [1], [1], and [0,1].
Example 2:
Input: nums = [1,0,1,0]
Output: 10
Explanation:
Every subarray of the array is alternating. There are 10 possible subarrays that we can choose.
Constraints:
1 <= nums.length <= 105
nums[i] is either 0 or 1.
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(n)
3101. Count Alternating Subarrays LeetCode Solution in C++
class Solution {
public:
long long countAlternatingSubarrays(vector<int>& nums) {
// dp[i] := the number of alternating subarrays ending in index i
vector<long> dp(nums.size(), 1);
for (int i = 1; i < nums.size(); ++i)
if (nums[i] != nums[i - 1])
dp[i] += dp[i - 1];
return accumulate(dp.begin(), dp.end(), 0L);
}
};
/* code provided by PROGIEZ */
3101. Count Alternating Subarrays LeetCode Solution in Java
class Solution {
public long countAlternatingSubarrays(int[] nums) {
// dp[i] := the number of alternating subarrays ending in index i
long[] dp = new long[nums.length];
Arrays.fill(dp, 1);
for (int i = 1; i < nums.length; ++i)
if (nums[i] != nums[i - 1])
dp[i] += dp[i - 1];
return Arrays.stream(dp).sum();
}
}
// code provided by PROGIEZ
3101. Count Alternating Subarrays LeetCode Solution in Python
class Solution:
def countAlternatingSubarrays(self, nums: list[int]) -> int:
# dp[i] := the number of alternating subarrays ending in index i
dp = [1] * len(nums)
for i in range(1, len(nums)):
if nums[i] != nums[i - 1]:
dp[i] += dp[i - 1]
return sum(dp)
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.