LeetCode 2720: Popularity Percentage Solution

Master LeetCode problem 2720 (Popularity Percentage), 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.

2720. Popularity Percentage

Problem Explanation

Explanation

To solve this problem, we need to calculate the popularity percentage for each item in a list of integers. The popularity percentage for an item is the percentage of occurrences of that item in the list. We will iterate through the list, count the occurrences of each item, and calculate the percentage based on the total number of items in the list.

Algorithm:

  1. Create a hashmap to store the count of each item in the list.
  2. Iterate through the list and increment the count for each item in the hashmap.
  3. Calculate the popularity percentage for each item by dividing its count by the total number of items and multiplying by 100.
  4. Return the hashmap with the popularity percentage for each item.

Time Complexity:

  • The time complexity of this algorithm is O(N), where N is the number of elements in the input list.

Space Complexity:

  • The space complexity of this algorithm is O(N) to store the hashmap.

Solution Code

import java.util.*;

public class Solution {
    public Map<Integer, Double> calculatePopularityPercentage(List<Integer> items) {
        Map<Integer, Double> popularityPercentage = new HashMap<>();
        Map<Integer, Integer> countMap = new HashMap<>();
        
        int totalItems = items.size();
        
        for (int item : items) {
            countMap.put(item, countMap.getOrDefault(item, 0) + 1);
        }
        
        for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
            double percentage = ((double) entry.getValue() / totalItems) * 100;
            popularityPercentage.put(entry.getKey(), percentage);
        }
        
        return popularityPercentage;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2720 (Popularity Percentage)?

This page provides optimized solutions for LeetCode problem 2720 (Popularity Percentage) 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 2720 (Popularity Percentage)?

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

Can I run code for LeetCode 2720 on DevExCode?

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

Back to LeetCode Solutions