3483. Alternating Groups II
My accepted Python solution to LeetCode problem 3483, Alternating Groups II, running in 737ms.
- Difficulty: Medium
- Python
- Runtime 737ms
- Memory 21.2MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 737ms, memory 21.2MB, accepted 2025-12-30.
class Solution:
def numberOfAlternatingGroups(self, colors: List[int], k: int) -> int:
n = len(colors)
# Extend the array to handle circular nature
extended = colors + colors[:k-1]
count = 0
streak = 1 # length of current alternating sequence
for i in range(1, len(extended)):
if extended[i] != extended[i-1]:
streak += 1
else:
streak = 1
# Check if we have a valid alternating group of size k
if streak >= k and i >= k - 1 and i < n + k - 1:
if i - k + 1 < n: # Starting position is in original array
count += 1
return count