Alternating Groups II

Medium Topics Company Tags

The binary array colors is arranged in a circle, so the last entry is followed by the first. For each starting position, consider the next k entries in circular order. Count how many of these groups have different values at every pair of adjacent positions within the group.

Count groups by their starting positions. The group may cross the end of the array; its own first and last entries do not need to differ unless they are adjacent inside its ordered sequence.

Example 1:

Alternating Groups II, example 1: illustration of the example

Input: colors = [0,1,0,1]
k = 3

Output: 4

Explanation: Every circular group of three entries alternates: the four starting positions produce [0,1,0], [1,0,1], [0,1,0], and [1,0,1]. The count is 4.

Example 2:

Alternating Groups II, example 2: illustration of the example

Input: colors = [0,0,0]
k = 3

Output: 0

Explanation: Every neighboring pair has equal values. No group of three alternates, so the count is zero.

Example 3:

Alternating Groups II, example 3: illustration of the example

Input: colors = [0,1,0]
k = 3

Output: 1

Explanation: Starting at index 0 gives [0,1,0], which alternates. The other starts produce [1,0,0] and [0,0,1], each containing equal neighbors, so only one group qualifies.

Constraints:

  • 3 <= colors.length <= 100000
  • colors[i] is either 0 or 1.
  • 3 <= k <= colors.length


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.