Bank Account Summary — LeetCode 1555 Python Solution

MediumLeetCode PremiumDatabase
Problem
#1555
Reading time
4 min

Table schema

SQL
Table: Users +--------------+---------+ | Column Name | Type | +--------------+---------+ | user_id | int | | user_name | varchar | | credit | int | +--------------+---------+ user_id is the primary key (column with unique values) for this table. Each row of this table contains the current credit information for each user.

Example

SQL
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| user_id      | int     |
| user_name    | varchar |
| credit       | int     |
+--------------+---------+
user_id is the primary key (column with unique values) for this table.
Each row of this table contains the current credit information for each user.

Python solution

Python
import duckdb
import pandas as pd

def solution(users: pd.DataFrame, transactions: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Users", users)
    con.register("Transactions", transactions)
    return con.execute("""SELECT
    t.user_id,
    user_name,
    SUM(t.credit) AS credit,
    IF(SUM(t.credit) < 0, 'Yes', 'No') AS credit_limit_breached
FROM
    (
        SELECT paid_by AS user_id, -amount AS credit FROM Transactions
        UNION ALL
        SELECT paid_to AS user_id, amount AS credit FROM Transactions
        UNION ALL
        SELECT user_id, credit FROM Users
    ) AS t
    JOIN Users AS u ON t.user_id = u.user_id
GROUP BY t.user_id;""").df()

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 1555. Bank Account Summary?
LeetCode 1555. Bank Account Summary is rated Medium on LeetCode.
What topics does LeetCode 1555. Bank Account Summary cover?
LeetCode 1555. Bank Account Summary is tagged Database on LeetCode.
Is LeetCode 1555. Bank Account Summary a premium problem?
Yes. LeetCode 1555. Bank Account Summary 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