Longest Apple Music Listening Session With At Most K Artists

Last updated: November 29, 2026

Quick Overview

Given the sequence of artist ids for songs a user played back to back, return the length of the longest contiguous listening session that includes at most k distinct artists.

Apple
Coding & Algorithms
Software Engineer
Apple
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


Given the sequence of artist ids for songs a user played back to back, return the length of the longest contiguous listening session that includes at most k distinct artists.

Apple Music recommendation and analytics teams use this framing to test sliding windows over play logs. The interviewer looks for a window that shrinks only when the distinct count exceeds k, and for clean bookkeeping of counts that drop to zero.

What the Interviewer Expects
  • Identify this as a variable-size sliding window
  • Track counts per artist and remove artists whose count reaches zero
  • Return the maximum window length
  • Handle k = 0 and empty input
  • Explain why the window is O(n) amortized
Key Topics to Cover
sliding window
hash maps
two pointers
distinct counting
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Return the session itself, not just its length.
  • Weight sessions by song duration and maximize total minutes instead.
  • Support many queries with different k values on the same log efficiently.
  • The log is unbounded; how do you keep memory bounded?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: list plays of artist ids, int k >= 0. Output: maximum length of a contiguous subarray with at most k distinct values. k = 0 or empty input returns 0....

High-Level Design

Maintain a window [left, right] and a dict of artist counts inside it. Extend right one play at a time. If the dict grows beyond k keys, advance left, decrementing counts and deleting keys that ...


Submit Your Answer
Markdown supported