Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't SortedSet be used as a Priority Queue or Min-Heap?

Tags:

c#

I was attempting to solve the running median problem (on hackerrank) using a sorted set. Only it's elements don't appear properly sorted.

See it in action here: http://rextester.com/NGBN25779

public class RunningMedian{

    List<int> list = new List<int>();
    SortedSet<int> sorted = new SortedSet<int>();

    public void Add(int num){
        list.Add(num);
        sorted.Add(num);
    }
    public double MedianNotWorking(){
        return GetMedian(sorted.ToArray());
    }
    public double MedianWorking(){
        int[] arr = list.ToArray();
        Array.Sort(arr);
        return GetMedian(arr);
    }
    public double GetMedian(int[] arr){
        int idx = list.Count / 2;
        if(arr.Length % 2 == 0){
            return (double)((double)(arr[idx] + arr[idx-1]) / 2);
        }else{
            return arr[idx];
        }
    }

}

static void Main(String[] args) {
    int n = Convert.ToInt32(Console.ReadLine());
    int[] a = new int[n];

    RunningMedian heap = new RunningMedian();
    for(int i = 0; i < n; i++){
        a[i] = Convert.ToInt32(Console.ReadLine());
        heap.Add(a[i]);

        //double median = heap.GetMedian();
        double median = heap.MedianNotWorking();
        Console.WriteLine(median.ToString("F1"));
    }
}

For the most part the sorted set does work. However at larger input sizes it begins to give wrong answers. It may not be the optimal solution to the problem but I'm curious as to why it fails at all. C# doesn't have a min-heap / priority queue so why can't sorted sets be used as a substitute?

*Edited to include full code from hackerrank.

Here is an input file. Input http://textuploader.com/dovni

Expected http://textuploader.com/dovnb

Output http://textuploader.com/dovwj

Conflicts appear near the end

Expected (Skipping 1-364) 54240.0 54576.5 54913.0 54576.5 54240.0

Results (Skipping 1-364) 54240.0 54576.5 54913.0 54963.0 54576.5

like image 280
Boyd Avatar asked Sep 15 '25 19:09

Boyd


1 Answers

SortedSet collections contain by definition only unique values. However your input file contains the number 21794 twice, which means that the second 21794 entry doesn't get added to your SortedSet. So your sorted set will contain fewer values than your list and your whole algorithm doesn't work anymore.

like image 118
Progman Avatar answered Sep 18 '25 10:09

Progman