Similar Problems

Similar Problems not available

Reported Posts - Leetcode Solution

Companies:

LeetCode:  Reported Posts Leetcode Solution

Difficulty: Easy

Topics: database  

The "Reported Posts" problem on LeetCode is a coding challenge that requires developers to find out which posts are reported the most. Given two arrays of integers, the first one representing post ids and the second one representing report ids, you must return the ids of the top k reported posts. Here is a detailed solution for the problem:

Step 1: Create a Dictionary

We need to create a dictionary to store the count of each reported post. First, create an empty dictionary where the keys will be post ids and the values will be the count of each report.

Step 2: Loop Through Report IDs

Next, iterate through the report ids array and check if the post id exists in the dictionary. If it exists, then increment its count by 1. If it does not exist, add the post id to the dictionary with a value of 1.

Step 3: Sort Dictionary

Now, we need to sort the dictionary by values in descending order so that we can easily retrieve the top k reported posts. To achieve this, use the sorted() function with a lambda function as the key. The lambda function takes the dictionary items and sorts them by the values in descending order.

Step 4: Return Top K Posts

Finally, return the top k post ids by slicing the sorted dictionary from 0 to k. Return them as a list.

Here is the Python solution for the Reported Posts problem on LeetCode:

def get_top_k(posts, reports, k):
    post_counts = {}

    for report_id in reports:
        if report_id in post_counts:
            post_counts[report_id] += 1
        else:
            post_counts[report_id] = 1

    sorted_posts = sorted(post_counts.items(), key=lambda x: x[1], reverse=True)

    top_k_posts = [post for post, count in sorted_posts[:k]]

    return top_k_posts

Usage:

posts = [1,2,3,4,5]
reports = [2,3,1,4,2,4,1,5,4,3,2,2]
k = 3

print(get_top_k(posts, reports, k)) # Output: [2, 4, 3]

This solution has a time complexity of O(n log n), which is due to the sorting of the dictionary.

Reported Posts Solution Code

1