Number of Transactions per Visit — LeetCode 1336 Python Solution

HardLeetCode PremiumDatabase
Problem
#1336
Reading time
7 min

Table schema

SQL
Table: Visits +---------------+---------+ | Column Name | Type | +---------------+---------+ | user_id | int | | visit_date | date | +---------------+---------+ (user_id, visit_date) is the primary key (combination of columns with unique values) for this table. Each row of this table indicates that user_id has visited the bank in visit_date.

Example

SQL
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user_id       | int     |
| visit_date    | date    |
+---------------+---------+
(user_id, visit_date) is the primary key (combination of columns with unique values) for this table.
Each row of this table indicates that user_id has visited the bank in visit_date.

Python solution

Python
import duckdb
import pandas as pd

def solution(visits: pd.DataFrame, transactions: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Visits", visits)
    con.register("Transactions", transactions)
    return con.execute("""WITH RECURSIVE
    S AS (
        SELECT 0 AS n
        UNION
        SELECT n + 1
        FROM S
        WHERE
            n < (
                SELECT MAX(cnt)
                FROM
                    (
                        SELECT COUNT(1) AS cnt
                        FROM Transactions
                        GROUP BY user_id, transaction_date
                    ) AS t
            )
    ),
    T AS (
        SELECT v.user_id, visit_date, IFNULL(cnt, 0) AS cnt
        FROM
            Visits AS v
            LEFT JOIN (
                SELECT user_id, transaction_date, COUNT(1) AS cnt
                FROM Transactions
                GROUP BY 1, 2
            ) AS t
                ON v.user_id = t.user_id AND v.visit_date = t.transaction_date
    )
SELECT n AS transactions_count, COUNT(user_id) AS visits_count
FROM
    S AS s
    LEFT JOIN T AS t ON s.n = t.cnt
GROUP BY n
ORDER BY n;""").df()

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 1336. Number of Transactions per Visit?
LeetCode 1336. Number of Transactions per Visit is rated Hard on LeetCode.
What topics does LeetCode 1336. Number of Transactions per Visit cover?
LeetCode 1336. Number of Transactions per Visit is tagged Database on LeetCode.
Is LeetCode 1336. Number of Transactions per Visit a premium problem?
Yes. LeetCode 1336. Number of Transactions per Visit 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