LINK02P10 - Editorial

Problem Link - Practice - Music Player

Problem Statement:

The functionality of a playlist queue needs to be implemented, i.e., adding a song to the queue, playing the next song, playing the previous song, switching to a song, etc.

Approach:

The key idea of this solution is to use a doubly linked list to manage the songs in the music player. Each song is represented by a node that contains the song ID and pointers to the previous and next songs. This structure allows for easy navigation between songs.

Here’s a breakdown of the approach:

  1. MusicPlayer Class:

    • head: A pointer to the first song in the list.
    • currentSong: A pointer to the song currently being played.
  2. addSong(int songId):

    • This function creates a new song node and adds it to the end of the list.
    • If the list is empty, the new song becomes both the head and the current song.
    • Otherwise, it traverses to the end of the list and links the new song.
  3. playNext():

    • Moves the current song pointer to the next song, if available.
  4. playPrev():

    • Moves the current song pointer to the previous song, if available.
  5. switchSong(int songId):

    • This function allows switching to a specific song by traversing the list until the song ID matches.
  6. current():

    • Returns the song ID of the song currently being played.

Time Complexity:

  • addSong: O(n) in the worst case, where n is the number of songs (traversing to the end).

  • playNext and playPrev: O(1) since they simply move the pointer.

  • switchSong: O(n) in the worst case, as it may need to traverse the entire list.

  • current: O(1) since it directly returns the current song’s ID.

Space Complexity:

  • O(n) because we store n nodes in the linked list, with each node representing a song.