Hi Team,
I was working with the SortedSet Data Structure and surprisingly I ended up finding an issue with the implementation.
When I tried to remove the first element from the SortedSet, It did not remove the element and while debugging I found Sorted Set returns false for the element which it returns as a result of First() method call.
Sample code:
public class Solution {
public int LeastInterval(char[] tasks, int n) {
if(tasks == null || tasks.Length == 0)
return 0;
// map of tasks with corresponding count.
Dictionary<char, int> map = new Dictionary<char, int>();
foreach(char task in tasks)
{
if(map.ContainsKey(task))
map[task]++;
else
map.Add(task, 1);
}
// Adding the tasks to SortedSet and sorting based on the task count in Dictionary.
SortedSet<char> uniqueTasks = new SortedSet<char>(Comparer<char>.Create((a,b) => map[b] > map[a] ? -1 : 1));
foreach(var c in map)
{
uniqueTasks.Add(c.Key);
}
int intervals = 0;
while(uniqueTasks.Count != 0)
{
IList<char> currentTaskList = new List<char>();
for(int i = 0; i <= n; i++)
{
if(uniqueTasks.Count == 0)
break;
// Here I get the first task
char currentTask = uniqueTasks.First();
// It is returning false, How can this be false????????
Console.WriteLine(uniqueTasks.Contains(uniqueTasks.First()));
Console.WriteLine(currentTask);
map[currentTask]--;
currentTaskList.Add(currentTask);
}
foreach(char t in currentTaskList)
{
if(map[t] > 0)
uniqueTasks.Add(t);
}
if(uniqueTasks.Count == 0)
intervals += n+1;
else
intervals += currentTaskList.Count;
}
return intervals;
}
}
/*
Sample Input
tasks = ["A","A","A","B","B","B"]
n = 2
*/