Round 1
Questions:
Design a system to track song plays and generate analytics based on the number of unique listeners per song. Implement the SongAnalytics
class with the following methods:
-
SongAnalytics()
Initializes the system. -
int add_song(string name)
Adds a song to the system, assigns it a unique auto-incrementing ID starting from1
, and returns the assigned ID. -
void play_song(int song_id, int user_id)
Records a play event for a song by a user.- If
song_id
does not exist, output:Error: Song ID <song_id> does not exist.
(replace<song_id>
with the invalid ID). - Each user is counted once per song, even if they play it multiple times.
- If
-
void print_analytics()
Prints a summary of all songs sorted by the number of unique listeners in descending order.- If two songs have the same number of unique listeners, sort them lexicographically by name in ascending order.
- Each line in the output should follow the format:
<song_name> (<count> unique listeners)
.
Example:
Input: add_song("Song A") → returns 1 add_song("Song B") → returns 2 add_song("Song C") → returns 3 play_song(1, 1) play_song(1, 2) play_song(2, 1) play_song(3, 3) play_song(3, 3) print_analytics() Output: Song A (2 unique listeners) Song B (1 unique listeners) Song C (1 unique listeners)
Explanation:
- "Song A" has 2 unique listeners.
- "Song B" and "Song C" both have 1 unique listener. They are sorted lexicographically by name ("Song B" before "Song C").
Note:
- Ensure the solution efficiently handles multiple calls to
play_song
andprint_analytics
.
Candidate's Approach
The candidate proposed implementing the SongAnalytics
class using a dictionary to store songs and a set to track unique listeners for each song. The add_song
method would increment an ID counter and store the song name in the dictionary. The play_song
method would check if the song ID exists and add the user ID to the set of listeners for that song. Finally, the print_analytics
method would sort the songs based on the number of unique listeners and print the results in the specified format.
Interviewer's Feedback
The interviewer appreciated the candidate's structured approach to the problem and their clear explanation of the methods. They suggested considering edge cases, such as handling invalid user IDs and ensuring the system can scale with a large number of songs and listeners.