Ctrl K

Two-Genre Stretch of a Playlist

Medium
A playlist has n tracks and genres[i] is the genre of track i. You want to pick a stretch of consecutive tracks and play all of it, but you are only in the mood for at most two different genres across the whole stretch. Return the greatest possible length of such a stretch.
Example 1
genres=[3, 0, 3, 1, 1, 3, 1] → 5

The last five tracks [3, 1, 1, 3, 1] use only genres 3 and 1. Reaching back to the 0 would make it three genres.

Example 2
genres=[2, 2, 2] → 3

The whole playlist is a single genre, so all of it can be played.

Example 3
genres=[0, 1, 2, 3, 4] → 2

Every genre is different, so at most two neighbouring tracks fit.

Constraints
  • 1 ≤ n = len(genres) ≤ 10⁵
  • 0 ≤ genres[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWindows With an Exact Alarm Count MediumStretches With k Odd Numbers MediumTwo Separate Segments With a Given Sum MediumTrim the Ends to a Target MediumRichest Repeat-Free Stretch Medium
loading Python…
Input
genres=[3, 0, 3, 1, 1, 3, 1]
Expected
5

Run checks the first 3 tests in your browser. Submit checks all 101 tests on the server, hidden ones included.