Pattern: Longest Substring With At Most K Distinct
mediumNot solved yet
The problem
A radio station's playlist is a list of artist names, in play order. Write a function that returns the length of the longest run of consecutive songs that uses at most k different artists. k is at least 0.
In the first example, the run "ana", "cy", "cy", "cy" has two artists and four songs. The run "ana", "bo", "ana" is shorter.
Write longest_with_k_artists(artists, k) in Python or longestWithKArtists(artists, k) in JavaScript.
Runs privately in your browser. Nothing is sent to a server.Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Write your function, then run it against 20 tests.
Breakdown
Stuck? Reveal one step at a time, and try again after each one.
The brute force
For each start, extend the end while the number of different artists stays at most k. Use a set to track artists. That's O(n²) time.
Step 2
Keep a window and count artists inside it
Slide a window over the playlist. Keep a map from artist to how many of their songs are in the window. The number of different artists is the number of keys in the map.
Step 3
Shrink when there are too many artists
After adding the song at right, if the map has more than k keys, move left forward: decrease the count of artists[left], and delete the key when its count reaches zero, until there are at most k artists again.
Step by step1 / 3
leftright
ana
0
bo
1
ana
2
cy
3
cy
4
cy
5
keysongs
ana2
bo1
cy1
Adding 'cy' makes 3 artists, one too many.
Step 4
Record the answer after shrinking
Now the window is valid, so right - left + 1 is a candidate for the longest run.
Solution
Give it a real try first: you learn far more from a wrong attempt than from reading the answer.
Use a sliding window with a map of counts. For each song, add it to the map. While the map has more than k artists, remove artists[left] from the window (deleting it from the map at zero) and move left on. Then update the best length.
python
1def longest_with_k_artists(artists, k):
2 in_window = {} # artist -> number of their songs in the window