User Activity for the Past 30 Days I — LeetCode 1141 Python Solution

EasyDatabase
Problem
#1141
Reading time
2 min

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("""SELECT activity_date AS day, COUNT(DISTINCT user_id) AS active_users
FROM Activity
WHERE activity_date <= '2019-07-27' AND DATEDIFF('2019-07-27', activity_date) < 30
GROUP BY 1;""").df()

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 1141. User Activity for the Past 30 Days I?
LeetCode 1141. User Activity for the Past 30 Days I is rated Easy on LeetCode.
What topics does LeetCode 1141. User Activity for the Past 30 Days I cover?
LeetCode 1141. User Activity for the Past 30 Days I is tagged Database on LeetCode.

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.

Get Stealth Interview