User Activity for the Past 30 Days II — LeetCode 1142 Python Solution
EasyLeetCode PremiumDatabase
- Problem
- #1142
- Reading time
- 3 min
- Source
- leetcode.com
Table schema
SQL
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
SQL
+---------------+---------+
| 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
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.