Leetcode 1148 - Article Views I
Problem
Examples
Solution
Method 1 - Using Distinct and Equality
Code
SQL
select distinct author_id as id from Views
where author_id = viewer_id
order by id;
Pandas
Create a new DataFrame named authors_viewed_own_articles by filtering the rows where the author_id and viewer_id are the same. This will give us the rows where authors viewed their own articles.
Extract the unique author_id values from the DataFrame authors_viewed_own_articles. We want to find the unique authors who viewed at least one of their own articles.
Sort the unique author_id values in ascending order to get the list of authors who viewed at least one of their own articles.
Create a new DataFrame named result_df with a single column named id containing the sorted unique author_id values.
Return the result_df, which will contain the list of authors who viewed at least one of their own articles, sorted by their IDs in ascending order.
import pandas as pd
def article_views(views: pd.DataFrame) -> pd.DataFrame:
authors_viewed_own_articles = views[views['author_id'] == views['viewer_id']]
unique_authors = authors_viewed_own_articles['author_id'].unique()
unique_authors = sorted(unique_authors)
result_df = pd.DataFrame({'id': unique_authors})
return result_df
Complexity
- Time:
O(n)
- Space:
O(1)