VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-playlist/

⇱ CSES Solutions - Playlist - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Playlist

Last Updated : 23 Jul, 2025

You are given a playlist of a radio station since its establishment. The playlist has a total of N songs. What is the longest sequence of successive songs where each song is unique?

Examples:

Input: N = 8, songs[] = {1, 2, 1, 3, 2, 7, 4, 2}
Output: 5
Explanation: The longest sequence of successive unique songs is: {1, 3, 2, 7, 4} which has 5 elements.

Input: N = 6, songs[] = {1, 2, 3, 1, 2, 3}
Output: 3
Explanation: The longest sequence of successive unique songs is: {1, 2, 3} which has 3 elements.

Approach: To solve the problem, follow the below idea:

The problem can be solved using a map to store the index of each character and two pointers: start and end to mark the starting and ending of the range of unique characters. Initially, we start from the first character and end at the first character. Then, we keep on shifting the end pointer and storing the index of each character in the map. If we encounter a character whose index > start pointer, then it means that in our window we already have that character. Then we will shrink the window by moving the start pointer to the previous index of the character + 1. This will maintain that all the character from start to end have unique characters.

Step-by-step algorithm:

  • Maintain two pointers, start = 0 and end = 0 to mark the starting and ending point of window.
  • Also maintain a map, say mp to store the last index of each character.
  • Iterate end from 0 to N - 1,
    • If the character at index = end is not present in the map, we insert the character along with the current index.
    • Otherwise, if the character is present in the map and its last occurrence is greater than the start of the window, it means that the current character is already present in the window. So, we need to shrink the window by moving start to last occurrence of that character + 1.
    • Also check for the maximum length of window (end - start + 1) in each iteration.
  • After all the iterations, print the maximum length of a window.

Below is the implementation of the algorithm:


Output
5

Time Complexity: O(N * logN), where N is the number of songs in the playlist.
Auxiliary Space: O(N)

Comment
Article Tags:
Article Tags: