![]() |
VOOZH | about |
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:
Below is the implementation of the algorithm:
5
Time Complexity: O(N * logN), where N is the number of songs in the playlist.
Auxiliary Space: O(N)