Similar Problems

Similar Problems not available

Article Views I - Leetcode Solution

Companies:

LeetCode:  Article Views I Leetcode Solution

Difficulty: Easy

Topics: database  

Problem Statement:

You are given a list of articles, where each article contains two fields: a unique identifier (ID) and a number of views.

Your task is to sort the articles in descending order of their number of views and return the IDs of the top k articles.

If two articles have the same number of views, the one with the smaller ID should be first.

You need to implement the following function:

def top_k_articles(articles: List[Tuple[str, int]], k: int) -> List[str]:

Solution:

The problem can be solved by sorting the list of articles according to the number of views in descending order and then selecting the top k articles.

In Python, we can use the sort() method to sort the list of articles based on the number of views. We can also use a lambda function to sort based on the second element in the tuple. To break ties, we sort the list based on the unique identifier in ascending order.

Once we have the sorted list of articles, we can simply select the top k articles and return their IDs.

Here's one possible solution:

from typing import List, Tuple

def top_k_articles(articles: List[Tuple[str, int]], k: int) -> List[str]:
    # Sort articles based on number of views and ID
    articles.sort(key=lambda x: (-x[1], x[0]))
    # Select the top k articles
    top_k = [article[0] for article in articles[:k]]
    return top_k

First, we sort the list of articles based on the number of views and then on the unique identifier using the lambda function. The key parameter takes the tuple and returns the two elements in the order that they should be sorted.

We use the -x[1] in the lambda function to sort in descending order, and x[0] to break the tie.

Finally, we select the top k articles and return their IDs using a list comprehension.

Note:

The time complexity of this solution is O(nlogn) due to the sorting operation.

Article Views I Solution Code

1