Consecutive Transactions with Increasing Amounts — LeetCode 2701 Python Solution
HardLeetCode PremiumDatabase
- Problem
- #2701
- Reading time
- 6 min
- Source
- leetcode.com
Table schema
SQL
Table: Transactions +------------------+------+ | Column Name | Type | +------------------+------+ | transaction_id | int | | customer_id | int | | transaction_date | date | | amount | int | +------------------+------+ transaction_id is the primary key of this table. Each row contains information about transactions that includes unique (customer_id, transaction_date) along with the corresponding customer_id and amount.Example
SQL
+------------------+------+
| Column Name | Type |
+------------------+------+
| transaction_id | int |
| customer_id | int |
| transaction_date | date |
| amount | int |
+------------------+------+
transaction_id is the primary key of this table.
Each row contains information about transactions that includes unique (customer_id, transaction_date) along with the corresponding customer_id and amount.Python solution
Python
import duckdb
import pandas as pd
def solution(transactions: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Transactions", transactions)
return con.execute("""WITH
T AS (
SELECT
t1.*,
SUM(
CASE
WHEN t2.customer_id IS NULL THEN 1
ELSE 0
END
) OVER (ORDER BY customer_id, transaction_date) AS s
FROM
Transactions AS t1
LEFT JOIN Transactions AS t2
ON t1.customer_id = t2.customer_id
AND t1.amount > t2.amount
AND DATEDIFF(t1.transaction_date, t2.transaction_date) = 1
)
SELECT
customer_id,
MIN(transaction_date) AS consecutive_start,
MAX(transaction_date) AS consecutive_end
FROM T
GROUP BY customer_id, s
HAVING COUNT(1) >= 3
ORDER BY customer_id;""").df()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 2701. Consecutive Transactions with Increasing Amounts?
- LeetCode 2701. Consecutive Transactions with Increasing Amounts is rated Hard on LeetCode.
- What topics does LeetCode 2701. Consecutive Transactions with Increasing Amounts cover?
- LeetCode 2701. Consecutive Transactions with Increasing Amounts is tagged Database on LeetCode.
- Is LeetCode 2701. Consecutive Transactions with Increasing Amounts a premium problem?
- Yes. LeetCode 2701. Consecutive Transactions with Increasing Amounts is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.