Using C# PriorityQueue in Remote Coding Interviews without .NET 6.0

Priority Queues are available in .NET 6.0. However, some companies that use HackerRank/CoderPad/etc. may not have updated to .NET 6.0 just yet and you will be unable to use Priority Queues for your solutions in that case. I’m not sure what is involved in updating those platforms, but I did encounter this once as an interviewee and strangely enough, I did not have this issue on the same platform but with a different company.

Here is a simple Priority Queue implementation that you can use. Most of the code is from this repository, but I added support for custom comparers and a peek method. Here is an example of it being used as a max heap to get the K smallest elements in a list.

Within my repository there is an example of it being used in the readme file.

Note that it is a good idea to familiarize yourself with the .NET 6.0 PriorityQueue and opt to use it where you can. One handy feature is that it allows you to specify an element and a separate priority value. This can be helpful in certain types of problems. For example, consider K Closest Points to Origin on LeetCode. The value you are keeping track of is the point itself, but the value you care about for the comparisons is the Euclidian distance from origin. With .NET 6.0’s PriorityQueue, you can accomplish this without having to make a custom class or tuple or something. In that case you would also have to make sure the custom comparer knows which value to look at in the tuple/class/etc. So it can be very helpful to have a “separation of duties” for TElement and TPriority.

 It can be a bit awkward if you just wanted to use it for integer values though, because in that case, TElement and TPriority will be the same thing, you will literally have to do:

maxHeap.Enqueue(1, 1);

to enqueue a value of 1.

Just food for thought, but hopefully my custom priority queue implementation will help you if you do not have access to .NET 6.0 for some reason. If you are using this for interviews, best of luck! Remember to stay calm and try to enjoy the challenge.

Leave a Reply

Your email address will not be published. Required fields are marked *