Talentd
FleetCode

3101. Count Alternating Subarrays

Medium57.6% acceptance1 company

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.

Asked at 1 company

Topics

Hints open one at a time

Hint 1
Try using dynamic programming.
Hint 2
Let dp[i] be the number of alternating subarrays ending at index i.
Hint 3
The final answer is the sum of dp[i] over all indices i from 0 to n - 1.
8:22
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def countAlternatingSubarrays(self, nums: List[int]) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
[0,1,1,1]
Input
[1,0,1,0]
Your code is saved on this device.Solution