LeetCode 2991: Top Three Wineries Solution

Master LeetCode problem 2991 (Top Three Wineries ), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2991. Top Three Wineries

Problem Explanation

Explanation:

To solve this problem, we can use a hashmap to keep track of the counts of each winery. We then iterate through the hashmap to find the top three wineries with the highest counts. We can achieve this by maintaining a min heap of size 3 to keep track of the top three wineries.

  1. Create a hashmap to store the counts of each winery.
  2. Iterate through the input list of wineries and update the counts in the hashmap.
  3. Initialize a min heap of size 3.
  4. Iterate through the entries in the hashmap:
    • If the size of the heap is less than 3, add the entry to the heap.
    • If the size of the heap is already 3, compare the count of the current entry with the root of the heap. If the count is greater than the root, remove the root and add the current entry to the heap.
  5. The top three wineries with the highest counts will be the elements in the heap.

Time complexity: O(n log k) where n is the number of wineries and k is 3 (size of the heap). Space complexity: O(n) for the hashmap and O(k) for the heap.

:

Solution Code

import java.util.*;

public List<String> topThreeWineries(List<String> wineries) {
    Map<String, Integer> counts = new HashMap<>();
    for (String winery : wineries) {
        counts.put(winery, counts.getOrDefault(winery, 0) + 1);
    }

    PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>(3, (a, b) -> a.getValue() - b.getValue());

    for (Map.Entry<String, Integer> entry : counts.entrySet()) {
        if (pq.size() < 3) {
            pq.offer(entry);
        } else {
            if (entry.getValue() > pq.peek().getValue()) {
                pq.poll();
                pq.offer(entry);
            }
        }
    }

    List<String> result = new ArrayList<>();
    while (!pq.isEmpty()) {
        result.add(0, pq.poll().getKey());
    }

    return result;
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2991 (Top Three Wineries )?

This page provides optimized solutions for LeetCode problem 2991 (Top Three Wineries ) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2991 (Top Three Wineries )?

The time complexity for LeetCode 2991 (Top Three Wineries ) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2991 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2991 in Java, C++, or Python.

Back to LeetCode Solutions