Two pointers and sliding window · Problem 3 of 3

Longest playlist stretch with at most k artists

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.

text
1longest_with_k_artists(["ana", "bo", "ana", "cy", "cy", "cy"], 2)  ->  4
2longest_with_k_artists(["ana", "bo", "cy"], 1)                     ->  1
3longest_with_k_artists(["ana", "ana"], 0)                          ->  0
Example 1, k = 2
ana
0
bo
1
ana
2
cy
3
cy
4
cy
5

Four songs in a row by just two artists.

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.

  1. Step 2
  2. Step 3
  3. Step 4

Solution

?

Give it a real try first: you learn far more from a wrong attempt than from reading the answer.