LeetCode 2820: Election Results Solution

Master LeetCode problem 2820 (Election Results), a medium 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.

2820. Election Results

Medium

Problem Explanation

Explanation:

To solve this problem, we can iterate through the given list of votes and keep track of the vote count for each candidate. We will then calculate the percentage of votes each candidate received and return the results sorted in descending order by percentage.

  • Create a hashmap to store the vote count for each candidate.
  • Iterate through the list of votes and update the count for each candidate in the hashmap.
  • Calculate the total number of votes.
  • Calculate the percentage of votes each candidate received.
  • Sort the candidates based on their vote percentage in descending order.

Time complexity: O(n log n) where n is the number of votes
Space complexity: O(n)

:

Solution Code

import java.util.*;

class Solution {
    public List<String> electionResults(List<String> votes) {
        Map<String, Integer> voteCount = new HashMap<>();
        for (String vote : votes) {
            voteCount.put(vote, voteCount.getOrDefault(vote, 0) + 1);
        }

        List<String> result = new ArrayList<>();
        int totalVotes = votes.size();
        for (String candidate : voteCount.keySet()) {
            double percentage = (double) voteCount.get(candidate) * 100 / totalVotes;
            result.add(candidate + ": " + String.format("%.2f", percentage) + "%");
        }

        Collections.sort(result, (a, b) -> {
            double percA = Double.parseDouble(a.substring(a.indexOf(":") + 2, a.indexOf("%")));
            double percB = Double.parseDouble(b.substring(b.indexOf(":") + 2, b.indexOf("%")));
            return Double.compare(percB, percA);
        });

        return result;
    }
}

Try It Yourself

Loading code editor...

Frequently Asked Questions

How to solve LeetCode 2820 (Election Results)?

This page provides optimized solutions for LeetCode problem 2820 (Election Results) 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 2820 (Election Results)?

The time complexity for LeetCode 2820 (Election Results) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2820 on DevExCode?

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

Back to LeetCode Solutions