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:
C++
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll solve(ll N, ll* songs)
{
ll start = 0, ans = 0;
// Map to store the last occurrence of all the
// characters
map<ll, ll> mp;
// Increment end pointer character by character
for (ll end = 0; end < N; end++) {
// If the current song is not present in the map
if (mp.find(songs[end]) == mp.end())
mp.insert({ songs[end], end });
else {
// If the current song is present in the map and
// is inside the window
if (mp[songs[end]] >= start)
start = mp[songs[end]] + 1;
// Update the last occurrence of current
// character to the current index
mp[songs[end]] = end;
}
// Update ans to store the maximum length of range
// of unique values
ans = max(ans, end - start + 1);
}
return ans;
}
int main()
{
// Sample Input
ll N = 8;
ll songs[N] = { 1, 2, 1, 3, 2, 7, 4, 2 };
cout << solve(N, songs) << "\n";
}
Java
import java.util.HashMap;
import java.util.Map;
public class Main {
static long solve(long N, long[] songs)
{
long start = 0, ans = 0;
// Map to store the last occurrence of all the
// characters
Map<Long, Long> mp = new HashMap<>();
// Increment end pointer character by character
for (long end = 0; end < N; end++) {
// If the current song is not present in the map
if (!mp.containsKey(songs[(int)end]))
mp.put(songs[(int)end], end);
else {
// If the current song is present in the map
// and is inside the window
if (mp.get(songs[(int)end]) >= start)
start = mp.get(songs[(int)end]) + 1;
// Update the last occurrence of current
// character to the current index
mp.put(songs[(int)end], end);
}
// Update ans to store the maximum length of
// range of unique values
ans = Math.max(ans, end - start + 1);
}
return ans;
}
public static void main(String[] args)
{
// Sample Input
long N = 8;
long[] songs = { 1, 2, 1, 3, 2, 7, 4, 2 };
System.out.println(solve(N, songs));
}
}
C#
using System;
using System.Collections.Generic;
public class MainClass {
public static long Solve(int N, int[] songs)
{
int start = 0;
long ans = 0;
Dictionary<int, int> mp
= new Dictionary<int, int>();
for (int end = 0; end < N; end++) {
if (!mp.ContainsKey(songs[end])) {
mp.Add(songs[end], end);
}
else {
if (mp[songs[end]] >= start) {
start = mp[songs[end]] + 1;
}
mp[songs[end]] = end;
}
ans = Math.Max(ans, end - start + 1);
}
return ans;
}
public static void Main(string[] args)
{
// Sample Input
int N = 8;
int[] songs = { 1, 2, 1, 3, 2, 7, 4, 2 };
Console.WriteLine(Solve(N, songs));
}
}
JavaScript
function solve(N, songs) {
let start = 0;
let ans = 0;
// Map to store the last occurrence of all the characters
let mp = new Map();
// Increment end pointer character by character
for (let end = 0; end < N; end++) {
// If the current song is not present in the map
if (!mp.has(songs[end])) {
mp.set(songs[end], end);
} else {
// If the current song is present in the map and is inside the window
if (mp.get(songs[end]) >= start) {
start = mp.get(songs[end]) + 1;
}
// Update the last occurrence of current character to the current index
mp.set(songs[end], end);
}
// Update ans to store the maximum length of range of unique values
ans = Math.max(ans, end - start + 1);
}
return ans;
}
// Sample Input
let N = 8;
let songs = [1, 2, 1, 3, 2, 7, 4, 2];
console.log(solve(N, songs));
Python3
def solve(N, songs):
start = 0
ans = 0
# Dictionary to store the last occurrence index of each song
mp = {}
# Iterate through the songs list
for end in range(N):
# If the current song is not present in the dictionary
if songs[end] not in mp:
mp[songs[end]] = end
else:
# If the current song is present in the dictionary and within the window
if mp[songs[end]] >= start:
start = mp[songs[end]] + 1
# Update the last occurrence of the current song to the current index
mp[songs[end]] = end
# Update 'ans' to store the maximum length of the range of unique values
ans = max(ans, end - start + 1)
return ans
def main():
# Sample Input
N = 8
songs = [1, 2, 1, 3, 2, 7, 4, 2]
print(solve(N, songs))
if __name__ == "__main__":
main()
Time Complexity: O(N * logN), where N is the number of songs in the playlist.
Auxiliary Space: O(N)
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Dynamic Programming or DP Dynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
What is an Operating System? An Operating System is a System software that manages all the resources of the computing device. Acts as an interface between the software and different parts of the computer or the computer hardware. Manages the overall resources and operations of the computer. Controls and monitors the execution o
5 min read