progress

~/problems / Sliding window

Repeat artists in every k-song stretch

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A radio station checks how varied its playlist feels. For every stretch of k consecutive songs, count the artists appearing two or more times in it.

Write repeat_artists(playlist: list[str], k: int) -> list[int] returning one count per stretch, left to right.

repeat_artists(["abba", "cher", "abba", "cher", "dido", "abba"], 4)
# [2, 1, 1]
# [abba cher abba cher] -> abba and cher repeat -> 2
# [cher abba cher dido] -> cher repeats         -> 1
# [abba cher dido abba] -> abba repeats         -> 1

repeat_artists(["x", "x", "x"], 2)   # [1, 1]   an artist counts once, however often they repeat

1 <= k <= len(playlist) <= 2 * 10^5. ⭐ Bonus: a speed test (n = 200,000, k = 20,000) earns a star in O(n).

Show hint

keep counts for the current stretch and a running repeats, updated when a count crosses between 1 and 2.

Topic: Sliding window. Grow right, shrink left while invalid; monotonic deque for window max/min.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc