LeetCode 1098: Unpopular Books Solution

Master LeetCode problem 1098 (Unpopular Books), 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.

1098. Unpopular Books

Medium

Problem Explanation

Explanation:

To solve this problem, we can use a hashmap to store the count of each book. Then, we can sort the hashmap based on the frequency of books and return the books which are unpopular (less than or equal to k).

  1. Create a hashmap to store the count of each book.
  2. Iterate through the given books array and populate the hashmap.
  3. Sort the hashmap based on the frequency of books.
  4. Iterate through the sorted hashmap and return the books that are unpopular (less than or equal to k).

Time Complexity: O(n log n) where n is the number of books Space Complexity: O(n)

:

Solution Code

import java.util.*;

class Solution {
    public List<Integer> findUnpopularBooks(int[] books, int k) {
        Map<Integer, Integer> bookCount = new HashMap<>();
        for (int book : books) {
            bookCount.put(book, bookCount.getOrDefault(book, 0) + 1);
        }
        
        List<Integer> result = new ArrayList<>();
        List<Map.Entry<Integer, Integer>> sortedBooks = new ArrayList<>(bookCount.entrySet());
        Collections.sort(sortedBooks, (a, b) -> a.getValue() - b.getValue());
        
        for (Map.Entry<Integer, Integer> entry : sortedBooks) {
            if (entry.getValue() <= k) {
                result.add(entry.getKey());
            }
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1098 (Unpopular Books)?

This page provides optimized solutions for LeetCode problem 1098 (Unpopular Books) 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 1098 (Unpopular Books)?

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

Can I run code for LeetCode 1098 on DevExCode?

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

Back to LeetCode Solutions