Leetcode #1127: User Purchase Platform
In this guide, we solve Leetcode #1127 User Purchase Platform in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: Yes
- Tags: Database
Intuition
The task is relational in nature, which maps cleanly to DataFrame operations in Python.
By treating tables as DataFrames, joins and group-bys become concise and readable.
Approach
Load the inputs as DataFrames and apply the appropriate merge, filter, or group-by.
Select or rename the columns to match the required output.
Steps:
- Load inputs as DataFrames.
- Apply merge/groupby/filter operations.
- Select the output columns.
Example
+-------------+---------+
| 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
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
The time complexity is O(n log n) (typical). The space complexity is O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.