EasyNo. 1142LeetCode Premium

User Activity for the Past 30 Days II — LeetCode 1142 Python Solution

Topics
Database
Reading time
3 min

Table schema

SQLTable 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

SQLExample
+---------------+---------+
| 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

PythonSolution
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

Related problems
No.ProblemDifficulty
0175Combine Two TablesEasy
0176Second Highest SalaryMedium
0177Nth Highest SalaryMedium
0178Rank ScoresMedium
0180Consecutive NumbersMedium
0181Employees Earning More Than Their ManagersEasy

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.