User Purchase Platform — LeetCode 1127 Python Solution
HardLeetCode PremiumDatabase
- Problem
- #1127
- Reading time
- 6 min
- Source
- leetcode.com
Table schema
SQL
Table: Spending +-------------+---------+ | Column Name | Type | +-------------+---------+ | user_id | int | | spend_date | date | | platform | enum | | amount | int | +-------------+---------+ The table logs the history of the spending of users that make purchases from an online shopping website that has a desktop and a mobile application. (user_id, spend_date, platform) is the primary key (combination of columns with unique values) of this table.Example
SQL
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| user_id | int |
| spend_date | date |
| platform | enum |
| amount | int |
+-------------+---------+
The table logs the history of the spending of users that make purchases from an online shopping website that has a desktop and a mobile application.
(user_id, spend_date, platform) is the primary key (combination of columns with unique values) of this table.
The platform column is an ENUM (category) type of ('desktop', 'mobile').Python solution
Python
import duckdb
import pandas as pd
def solution(spending: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Spending", spending)
return con.execute("""WITH
P AS (
SELECT DISTINCT spend_date, 'desktop' AS platform FROM Spending
UNION
SELECT DISTINCT spend_date, 'mobile' FROM Spending
UNION
SELECT DISTINCT spend_date, 'both' FROM Spending
),
T AS (
SELECT
user_id,
spend_date,
SUM(amount) AS amount,
IF(COUNT(platform) = 1, platform, 'both') AS platform
FROM Spending
GROUP BY 1, 2
)
SELECT
p.*,
IFNULL(SUM(amount), 0) AS total_amount,
COUNT(t.user_id) AS total_users
FROM
P AS p
LEFT JOIN T AS t USING (spend_date, platform)
GROUP BY 1, 2;""").df()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 1127. User Purchase Platform?
- LeetCode 1127. User Purchase Platform is rated Hard on LeetCode.
- What topics does LeetCode 1127. User Purchase Platform cover?
- LeetCode 1127. User Purchase Platform is tagged Database on LeetCode.
- Is LeetCode 1127. User Purchase Platform a premium problem?
- Yes. LeetCode 1127. User Purchase Platform is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.