Monthly Transactions II — LeetCode 1205 Python Solution

MediumLeetCode PremiumDatabase
Problem
#1205
Reading time
5 min

Table schema

SQL
Table: Transactions +----------------+---------+ | Column Name | Type | +----------------+---------+ | id | int | | country | varchar | | state | enum | | amount | int | | trans_date | date | +----------------+---------+ id is the column of unique values of this table. The table has information about incoming transactions.

Example

SQL
+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| id             | int     |
| country        | varchar |
| state          | enum    |
| amount         | int     |
| trans_date     | date    |
+----------------+---------+
id is the column of unique values of this table.
The table has information about incoming transactions.
The state column is an ENUM (category) of type ["approved", "declined"].

Python solution

Python
import duckdb
import pandas as pd

def solution(transactions: pd.DataFrame, chargebacks: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Transactions", transactions)
    con.register("Chargebacks", chargebacks)
    return con.execute("""WITH
    T AS (
        SELECT * FROM Transactions
        UNION
        SELECT id, country, 'chargeback', amount, c.trans_date
        FROM
            Transactions AS t
            JOIN Chargebacks AS c ON t.id = c.trans_id
    )
SELECT
    DATE_FORMAT(trans_date, '%Y-%m') AS month,
    country,
    SUM(state = 'approved') AS approved_count,
    SUM(IF(state = 'approved', amount, 0)) AS approved_amount,
    SUM(state = 'chargeback') AS chargeback_count,
    SUM(IF(state = 'chargeback', amount, 0)) AS chargeback_amount
FROM T
GROUP BY 1, 2
HAVING approved_amount OR chargeback_amount;""").df()

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 1205. Monthly Transactions II?
LeetCode 1205. Monthly Transactions II is rated Medium on LeetCode.
What topics does LeetCode 1205. Monthly Transactions II cover?
LeetCode 1205. Monthly Transactions II is tagged Database on LeetCode.
Is LeetCode 1205. Monthly Transactions II a premium problem?
Yes. LeetCode 1205. Monthly Transactions 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.

Get Stealth Interview