Java Priority Queue | HackerRank Programming Solutions | HackerRank Java Solutions

Hello Programmers/Coders, Today we are going to share solutions of Programming problems of HackerRank of Programming Language Java . At Each Problem with Successful submission with all Test Cases Passed, you will get an score or marks. And after solving maximum problems, you will be getting stars. This will highlight your profile to the recruiters.

In this post, you will find the solution for Java Priority Queue-HackerRank Problem. We are providing the correct and tested solutions of coding problems present on HackerRank. If you are not able to solve any problem, then you can take help from our Blog/website.

Use “Ctrl+F” To Find Any Questions Answer. & For Mobile User, You Just Need To Click On Three dots In Your Browser & You Will Get A “Find” Option There. Use These Option to Get Any Random Questions Answer.

Introduction To Java

JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1991, later acquired by Oracle Corporation. It is a simple programming language. Java makes writing, compiling, and debugging programming easy. It helps to create reusable code and modular programs.

Java is a class-based, object-oriented programming language and is designed to have as few implementation dependencies as possible. A general-purpose programming language made for developers to write once run anywhere that is compiled Java code can run on all platforms that support Java. Java applications are compiled to byte code that can run on any Java Virtual Machine. The syntax of Java is similar to c/c++.

Link for the ProblemJava Priority Queue – Hacker Rank Solution

Java Priority Queue – Hacker Rank Solution

Problem :

In computer science, a priority queue is an abstract data type which is like a regular queue, but where additionally each element has a “priority” associated with it. In a priority queue, an element with high priority is served before an element with low priority. – Wikipedia


In this problem we will test your knowledge on Java Priority Queue.

There are a number of students in a school who wait to be served. Two types of events, ENTER and SERVED, can take place which are described below.

  • ENTER: A student with some priority enters the queue to be served.
  • SERVED: The student with the highest priority is served (removed) from the queue.

A unique id is assigned to each student entering the queue. The queue serves the students based on the following criteria (priority criteria):

  1. The student having the highest Cumulative Grade Point Average (CGPA) is served first.
  2. Any students having the same CGPA will be served by name in ascending case-sensitive alphabetical order.
  3. Any students having the same CGPA and name will be served in ascending order of the id.

Create the following two classes:

  • The Student class should implement:
    • The constructor Student(int id, String name, double cgpa).
    • The method int getID() to return the id of the student.
    • The method String getName() to return the name of the student.
    • The method double getCGPA() to return the CGPA of the student.
  • The Priorities class should implement the method List<Student> getStudents(List<String> events) to process all the given events and return all the students yet to be served in the priority order.

Input Format

The first line contains an integer, , describing the total number of events. Each of the  subsequent lines will be of the following two forms:

  • ENTER name CGPA id: The student to be inserted into the priority queue.
  • SERVED: The highest priority student in the queue was served.

The locked stub code in the editor reads the input and tests the correctness of the Student and Priorities classes implementation.

Constraints

Output Format

The locked stub code prints the names of the students yet to be served in the priority order. If there are no such student, then the code prints EMPTY.

Sample Input 0

12
ENTER John 3.75 50
ENTER Mark 3.8 24
ENTER Shafaet 3.7 35
SERVED
SERVED
ENTER Samiha 3.85 36
SERVED
ENTER Ashley 3.9 42
ENTER Maria 3.6 46
ENTER Anik 3.95 49
ENTER Dan 3.95 50
SERVED

Sample Output 0

Dan
Ashley
Shafaet
Maria

Explanation 0

In this case, the number of events is 12. Let the name of the queue be Q.

  • John is added to Q. So, it contains (John, 3.75, 50).
  • Mark is added to Q. So, it contains (John, 3.75, 50) and (Mark, 3.8, 24).
  • Shafaet is added to Q. So, it contains (John, 3.75, 50), (Mark, 3.8, 24), and (Shafaet, 3.7, 35).
  • Mark is served as he has the highest CGPA. So, Q contains (John, 3.75, 50) and (Shafaet, 3.7, 35).
  • John is served next as he has the highest CGPA. So, Q contains (Shafaet, 3.7, 35).
  • Samiha is added to Q. So, it contains (Shafaet, 3.7, 35) and (Samiha, 3.85, 36).
  • Samiha is served as she has the highest CGPA. So, Q contains (Shafaet, 3.7, 35).
  • Now, four more students are added to Q. So, it contains (Shafaet, 3.7, 35), (Ashley, 3.9, 42), (Maria, 3.6, 46), (Anik, 3.95, 49), and (Dan, 3.95, 50).
  • Anik is served because though both Anil and Dan have the highest CGPA but Anik comes first when sorted in alphabetic order. So, Q contains (Dan, 3.95, 50), (Ashley, 3.9, 42), (Shafaet, 3.7, 35), and (Maria, 3.6, 46).

As all events are completed, the name of each of the remaining students is printed on a new line.

Java Priority Queue – Hacker Rank Solution
  
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Comparator;
import java.util.PriorityQueue;

class Student {
    private final int id;
    private final String name;
    private final double cgpa;

    public Student(int id, String name, double cgpa) {
        this.id = id;
        this.name = name;
        this.cgpa = cgpa;
    }

    public int getID() {
        return id;
    }

    public String getName() {
        return name;
    }

    public double getCGPA() {
        return cgpa;
    }
}

class Priorities {
    
    private final PriorityQueue<Student> queue = new PriorityQueue<>(
            Comparator.comparing(Student::getCGPA).reversed()
                    .thenComparing(Student::getName)
                    .thenComparing(Student::getID));

    public List<Student> getStudents(List<String> events) {
        events.forEach((event) -> {
            if (event.equals("SERVED")) {
                queue.poll();
            } else {
                String[] details = event.split(" ");

                queue.add(new Student(Integer.parseInt(details[3]), details[1], Double.parseDouble(details[2])));
            }
        });

        List<Student> students = new ArrayList<>();
        while (!queue.isEmpty()) {
            students.add(queue.poll());
        }

        return students;
    }
}

public class Solution {
    
    private final static Scanner scan = new Scanner(System.in);
    private final static Priorities priorities = new Priorities();

    public static void main(String[] args) {
        int totalEvents = Integer.parseInt(scan.nextLine());
        List<String> events = new ArrayList<>();

        while (totalEvents-- != 0) {
            String event = scan.nextLine();
            events.add(event);
        }

        List<Student> students = priorities.getStudents(events);

        if (students.isEmpty()) {
            System.out.println("EMPTY");
        } else {
            for (Student st : students) {
                System.out.println(st.getName());
            }
        }
    }
}

609 thoughts on “Java Priority Queue | HackerRank Programming Solutions | HackerRank Java Solutions”

  1. I discovered your blog website on google and verify just a few of your early posts. Continue to maintain up the excellent operate. I simply further up your RSS feed to my MSN News Reader. In search of ahead to reading more from you in a while!…

    Reply
  2. I¦ve been exploring for a little for any high quality articles or blog posts on this sort of house . Exploring in Yahoo I eventually stumbled upon this web site. Studying this information So i¦m glad to show that I’ve an incredibly good uncanny feeling I found out just what I needed. I so much indisputably will make sure to do not disregard this site and provides it a look regularly.

    Reply
  3. Thank you for the sensible critique. Me & my neighbor were just preparing to do some research about this. We got a grab a book from our local library but I think I learned more from this post. I am very glad to see such fantastic information being shared freely out there.

    Reply
  4. Great work! This is the kind of info that should be shared across the internet.
    Shame on the search engines for no longer positioning this put
    up higher! Come on over and seek advice from my web
    site . Thanks =)

    Reply
  5. Simply want to say your article is as astounding. The clarity in your post is just great and i could suppose you’re an expert in this subject. Fine along with your permission let me to grasp your feed to stay updated with drawing close post. Thank you a million and please carry on the enjoyable work.

    Reply
  6. Pretty portion of content. I simply stumbled upon your weblog and in accession capital to say that I get actually loved account your blog posts. Any way I will be subscribing in your augment and even I success you get entry to persistently quickly.

    Reply
  7. I was curious if you ever considered changing the structure of your blog? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or 2 images. Maybe you could space it out better?

    Reply
  8. Thanks for sharing superb informations. Your web site is very cool. I am impressed by the details that you’ve on this website. It reveals how nicely you perceive this subject. Bookmarked this web page, will come back for more articles. You, my friend, ROCK! I found just the information I already searched all over the place and simply couldn’t come across. What a great site.

    Reply
  9. Good post. I learn one thing tougher on completely different blogs everyday. It’ll always be stimulating to learn content material from other writers and practice a bit something from their store. I’d favor to use some with the content material on my weblog whether you don’t mind. Natually I’ll offer you a link on your internet blog. Thanks for sharing.

    Reply
  10. There are actually a number of details like that to take into consideration. That could be a great point to convey up. I offer the thoughts above as general inspiration however clearly there are questions just like the one you convey up where crucial factor shall be working in trustworthy good faith. I don?t know if finest practices have emerged around issues like that, however I’m certain that your job is clearly recognized as a fair game. Each girls and boys really feel the affect of only a moment’s pleasure, for the rest of their lives.

    Reply
  11. I think this is one of the most significant information for me. And i’m glad reading your article. But wanna remark on few general things, The website style is great, the articles is really excellent : D. Good job, cheers

    Reply
  12. Thank you for any other informative web site. Where else may I am getting that kind of info written in such a perfect means? I have a project that I am simply now running on, and I have been at the glance out for such information.

    Reply
  13. Hey there would you mind stating which blog platform you’re working with? I’m looking to start my own blog in the near future but I’m having a tough time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I’m looking for something completely unique. P.S My apologies for getting off-topic but I had to ask!

    Reply
  14. Hello! I could have sworn I’ve been to this blog before but after reading through some of the post I realized it’s new to me. Nonetheless, I’m definitely happy I found it and I’ll be bookmarking and checking back often!

    Reply
  15. You really make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand. It seems too complicated and very broad for me. I am looking forward for your next post, I will try to get the hang of it!

    Reply
  16. It is appropriate time to make a few plans for the longer term and it is time to be happy. I have read this post and if I may I wish to recommend you few interesting things or suggestions. Perhaps you could write next articles relating to this article. I wish to read more things approximately it!

    Reply
  17. Wow that was strange. I just wrote an very long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Regardless, just wanted to say wonderful blog!

    Reply
  18. I have been surfing online more than three hours these days, yet I never found any interesting article like yours. It’s lovely value enough for me. In my opinion, if all website owners and bloggers made just right content as you did, the internet will probably be much more useful than ever before.

    Reply
  19. It is appropriate time to make a few plans for the future and it is time to be happy. I have read this submit and if I may just I want to recommend you few interesting things or advice. Perhaps you could write next articles referring to this article. I wish to read more things approximately it!

    Reply
  20. Hey there would you mind stating which blog platform you’re working with? I’m planning to start my own blog in the near future but I’m having a tough time making a decision between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I’m looking for something completely unique. P.S Apologies for getting off-topic but I had to ask!

    Reply
  21. I don’t even understand how I stopped up here, however I assumed this submit was good. I don’t realize who you’re however definitely you are going to a famous blogger if you are not already. Cheers!

    Reply
  22. It’s in point of fact a nice and helpful piece of information. I’m satisfied that you shared this helpful info with us. Please stay us informed like this. Thanks for sharing.

    Reply
  23. Thank you for any other informative web site. Where else may just I am getting that kind of info written in such a perfect way? I have a project that I am simply now operating on, and I have been at the glance out for such information.

    Reply
  24. Wonderful goods from you, man. I’ve keep in mind your stuff prior to and you’re simply too great. I really like what you’ve obtained here, really like what you’re stating and the best way through which you are saying it. You make it entertaining and you still take care of to stay it smart. I can not wait to read far more from you. This is actually a wonderful website.

    Reply
  25. To read verified dispatch, adhere to these tips:

    Look in behalf of credible sources: http://levegroup.com/include/pages/?what-is-gnd-news-all-you-need-to-know.html. It’s eminent to ensure that the news outset you are reading is reliable and unbiased. Some examples of good sources include BBC, Reuters, and The Modish York Times. Review multiple sources to stimulate a well-rounded understanding of a precisely statement event. This can support you listen to a more ideal facsimile and keep bias. Be hep of the perspective the article is coming from, as set respectable hearsay sources can be dressed bias. Fact-check the information with another origin if a communication article seems too lurid or unbelievable. Always be inevitable you are reading a known article, as tidings can substitute quickly.

    Close to following these tips, you can evolve into a more in the know dispatch reader and more intelligent be aware the cosmos everywhere you.

    Reply
  26. What’s Taking place i’m new to this, I stumbled upon this I have found It positively helpful and it has helped me out loads. I hope to give a contribution & aid other users like its helped me. Good job.

    Reply
  27. Altogether! Declaration info portals in the UK can be crushing, but there are numerous resources ready to boost you espy the unmatched the same because you. As I mentioned already, conducting an online search representing https://lodgenine.co.uk/art/jennifer-griffin-s-age-fox-news-anchor-s-birthdate.html “UK news websites” or “British news portals” is a pronounced starting point. Not no more than purposefulness this grant you a encyclopaedic shopping list of report websites, but it will also afford you with a improved pact of the current story landscape in the UK.
    In the good old days you have a itemize of future rumour portals, it’s prominent to value each sole to determine which best suits your preferences. As an example, BBC Intelligence is known in place of its ambition reporting of report stories, while The Guardian is known quest of its in-depth criticism of governmental and social issues. The Disinterested is known pro its investigative journalism, while The Times is known for its business and finance coverage. By way of concession these differences, you can decide the talk portal that caters to your interests and provides you with the newsflash you have a yen for to read.
    Additionally, it’s quality looking at close by expos‚ portals because proper to regions within the UK. These portals provide coverage of events and news stories that are akin to the area, which can be specially cooperative if you’re looking to safeguard up with events in your town community. In behalf of instance, shire communiqu‚ portals in London classify the Evening Canon and the Londonist, while Manchester Evening Scuttlebutt and Liverpool Repercussion are stylish in the North West.
    Blanket, there are many statement portals available in the UK, and it’s high-level to do your digging to unearth the everybody that suits your needs. By means of evaluating the different low-down portals based on their coverage, dash, and essay viewpoint, you can choose the individual that provides you with the most relevant and captivating news stories. Good fortunes with your search, and I anticipate this data helps you come up with the correct expos‚ portal since you!

    Reply
  28. After looking into a few of the blog posts on your website, I honestly like your way of blogging. I saved it to my bookmark site list and will be checking back soon. Please check out my web site as well and let me know how you feel.

    Reply
  29. Undeniably believe that which you stated. Your favorite justification appeared to be on the internet the simplest thing to be aware of. I say to you, I definitely get irked while people consider worries that they plainly do not know about. You managed to hit the nail upon the top and also defined out the whole thing without having side effect , people can take a signal. Will likely be back to get more. Thanks

    Reply
  30. Nice post. I used to be checking continuously this blog and I am inspired! Very useful information particularly the ultimate phase 🙂 I deal with such info a lot. I used to be seeking this particular info for a long timelong time. Thank you and good luck.

    Reply
  31. I loved as much as you will receive carried out right here. The sketch is tasteful, your authored subject matter stylish. nonetheless, you command get bought an impatience over that you wish be delivering the following. unwell unquestionably come further formerly again since exactly the same nearly a lot often inside case you shield this increase.

    Reply
  32. My coder is trying to persuade me to move to .net from PHP. I have always disliked the idea because of the expenses. But he’s tryiong none the less. I’ve been using Movable-type on several websites for about a year and am nervous about switching to another platform. I have heard very good things about blogengine.net. Is there a way I can transfer all my wordpress content into it? Any kind of help would be really appreciated!

    Reply
  33. Не знаете, какой подрядчик выбрать для устройства стяжки пола? Обратитесь к нам на сайт styazhka-pola24.ru! Мы предоставляем услуги по залитию стяжки пола любой площади и сложности, а также гарантируем высокое качество работ и доступные цены.

    Reply
  34. Доверьте оштукатуривание стен профессионалам с сайта mehanizirovannaya-shtukaturka-moscow.ru. Экономьте свое время и силы!

    Reply
  35. I absolutely love your blog and find a lot of your post’s to be exactly I’m looking for. Does one offer guest writers to write content available for you? I wouldn’t mind producing a post or elaborating on a few of the subjects you write about here. Again, awesome web log!

    Reply
  36. You can definitely see your enthusiasm in the article you write. The world hopes for more passionate writers like you who aren’t afraid to mention how they believe. All the time go after your heart.

    Reply
  37. My coder is trying to persuade me to move to .net from PHP. I have always disliked the idea because of the costs. But he’s tryiong none the less. I’ve been using WordPress on numerous websites for about a year and am worried about switching to another platform. I have heard very good things about blogengine.net. Is there a way I can transfer all my wordpress posts into it? Any kind of help would be greatly appreciated!

    Reply
  38. Sight Care is a daily supplement proven in clinical trials and conclusive science to improve vision by nourishing the body from within. The Sight Care formula claims to reverse issues in eyesight, and every ingredient is completely natural.

    Reply
  39. Cortexi is a completely natural product that promotes healthy hearing, improves memory, and sharpens mental clarity. Cortexi hearing support formula is a combination of high-quality natural components that work together to offer you with a variety of health advantages, particularly for persons in their middle and late years. Cortex not only improves hearing but also decreases inflammation, eliminates brain fog, and gives natural memory protection.

    Reply
  40. Boostaro increases blood flow to the reproductive organs, leading to stronger and more vibrant erections. It provides a powerful boost that can make you feel like you’ve unlocked the secret to firm erections

    Reply
  41. Puravive introduced an innovative approach to weight loss and management that set it apart from other supplements. It enhances the production and storage of brown fat in the body, a stark contrast to the unhealthy white fat that contributes to obesity.

    Reply
  42. FitSpresso stands out as a remarkable dietary supplement designed to facilitate effective weight loss. Its unique blend incorporates a selection of natural elements including green tea extract, milk thistle, and other components with presumed weight loss benefits.

    Reply
  43. Neotonics is an essential probiotic supplement that works to support the microbiome in the gut and also works as an anti-aging formula. The formula targets the cause of the aging of the skin.

    Reply
  44. EyeFortin is a natural vision support formula crafted with a blend of plant-based compounds and essential minerals. It aims to enhance vision clarity, focus, and moisture balance.

    Reply
  45. The Quietum Plus supplement promotes healthy ears, enables clearer hearing, and combats tinnitus by utilizing only the purest natural ingredients. Supplements are widely used for various reasons, including boosting energy, lowering blood pressure, and boosting metabolism.

    Reply
  46. GlucoBerry is one of the biggest all-natural dietary and biggest scientific breakthrough formulas ever in the health industry today. This is all because of its amazing high-quality cutting-edge formula that helps treat high blood sugar levels very naturally and effectively.

    Reply
  47. Kerassentials are natural skin care products with ingredients such as vitamins and plants that help support good health and prevent the appearance of aging skin. They’re also 100% natural and safe to use. The manufacturer states that the product has no negative side effects and is safe to take on a daily basis. Kerassentials is a convenient, easy-to-use formula.

    Reply
  48. Cortexi is an effective hearing health support formula that has gained positive user feedback for its ability to improve hearing ability and memory. This supplement contains natural ingredients and has undergone evaluation to ensure its efficacy and safety. Manufactured in an FDA-registered and GMP-certified facility, Cortexi promotes healthy hearing, enhances mental acuity, and sharpens memory.

    Reply
  49. Sight Care is a daily supplement proven in clinical trials and conclusive science to improve vision by nourishing the body from within. The Sight Care formula claims to reverse issues in eyesight, and every ingredient is completely natural.

    Reply
  50. Насладитесь простотой и динамикой Lucky Jet, где каждый полет может умножить вашу ставку. Войдите в игру через сайт 1win и пускайте удачу в небо!

    Reply
  51. My partner and I absolutely love your blog and find most of your post’s to be precisely what I’m looking for. Do you offer guest writers to write content available for you? I wouldn’t mind producing a post or elaborating on some of the subjects you write in relation to here. Again, awesome web site!

    Reply
  52. Your article is excellent! The information is presented clearly, and I’m curious if you plan to add more images in your upcoming pieces. It could enhance the overall reader experience.

    Reply
  53. This article is incredible! The way it clarifies things is truly captivating and extremely easy to follow. It’s clear that a lot of work and investigation went into this, which is indeed noteworthy. The author has managed to make the subject not only fascinating but also delightful to read. I’m wholeheartedly excited about exploring more content like this in the forthcoming. Thanks for sharing, you’re doing an remarkable task!

    Reply
  54. Hey there! I’ve been following your weblog for a while now and finally got the bravery to go ahead and give you a shout out from Kingwood Tx! Just wanted to tell you keep up the fantastic job!

    Reply