Skip to main content
Back to problems
Leetcode
Medium
Arrays
Greedy
Sliding Window
Alternating Groups II

Count the number of contiguous circular segments that alternate between two values and satisfy a minimum length condition.

Acceptance 0%
Problem Statement

You are given a circular array of colors, represented as integers. A contiguous group is alternating if every adjacent pair of elements in the group has different values.

Because the array is circular, groups may wrap around from the end back to the beginning. Your task is to count how many contiguous groups satisfy the alternating condition and a required minimum length.

In practice, this kind of problem asks you to scan the array efficiently and recognize maximal alternating stretches, then derive how many valid groups they contribute.

Input Format

  • An integer array colors of length n.
  • An integer k representing the minimum required length of a valid alternating group.

The array is considered circular, so the last element is adjacent to the first element.

Output Format

Return the number of contiguous circular subarrays of length at least k that are alternating.

Constraints

  • 1n1 \le n
  • Elements are integers that can be compared for equality.
  • The array is circular.
  • Use an approach that is efficient for large n.
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

4

Explanation

Every circular subarray of length 3 or 4 is alternating in this array, so all 4 valid groups are counted.

Example 2

Input

colors = [1,1,0,1], k = 2

Output

4

Explanation

The alternating circular groups of length at least 2 are [1,0], [0,1], [1,0,1], and [0,1,1] is not alternating because the last two values are equal.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.