EasyNo. 1142LeetCode Premium
User Activity for the Past 30 Days II — LeetCode 1142 Python Solution
- Topics
- Database
- Reading time
- 3 min
- Source
- leetcode.com
Table schema
Table: Activity +---------------+---------+ | Column Name | Type | +---------------+---------+ | user_id | int | | session_id | int | | activity_date | date | | activity_type | enum | +---------------+---------+ This table may have duplicate rows. The activity_type column is an ENUM (category) of type ('open_session', 'end_session', 'scroll_down', 'send_message').Example
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| user_id | int |
| session_id | int |
| activity_date | date |
| activity_type | enum |
+---------------+---------+
This table may have duplicate rows.
The activity_type column is an ENUM (category) of type ('open_session', 'end_session', 'scroll_down', 'send_message').
The table shows the user activities for a social media website.
Note that each session belongs to exactly one user.Python solution
import duckdb
import pandas as pd
def solution(activity: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Activity", activity)
return con.execute("""WITH
T AS (
SELECT
COUNT(DISTINCT session_id) AS sessions
FROM Activity
WHERE activity_date <= '2019-07-27' AND DATEDIFF('2019-07-27', activity_date) < 30
GROUP BY user_id
)
SELECT IFNULL(ROUND(AVG(sessions), 2), 0) AS average_sessions_per_user
FROM T;""").df()Complexity
- Time
- O(n log n)(typical)
- Space · auxiliary
- O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0175 | Combine Two Tables | Easy |
| 0176 | Second Highest Salary | Medium |
| 0177 | Nth Highest Salary | Medium |
| 0178 | Rank Scores | Medium |
| 0180 | Consecutive Numbers | Medium |
| 0181 | Employees Earning More Than Their Managers | Easy |
Frequently asked questions
- How hard is LeetCode 1142. User Activity for the Past 30 Days II?
LeetCode 1142. User Activity for the Past 30 Days II is rated Easy on LeetCode.
- What topics does LeetCode 1142. User Activity for the Past 30 Days II cover?
LeetCode 1142. User Activity for the Past 30 Days II is tagged Database on LeetCode.
- Is LeetCode 1142. User Activity for the Past 30 Days II a premium problem?
Yes. LeetCode 1142. User Activity for the Past 30 Days II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.