Leetcode #1843: Suspicious Bank Accounts
In this guide, we solve Leetcode #1843 Suspicious Bank Accounts 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: Accounts +----------------+------+ | Column Name | Type | +----------------+------+ | account_id | int | | max_income | int | +----------------+------+ account_id is the column with unique values for this table. Each row contains information about the maximum monthly income for one bank account.
Quick Facts
- Difficulty: Medium
- 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 |
+----------------+------+
| account_id | int |
| max_income | int |
+----------------+------+
account_id is the column with unique values for this table.
Each row contains information about the maximum monthly income for one bank account.
Python Solution
import duckdb
import pandas as pd
def solution(accounts: pd.DataFrame, transactions: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Accounts", accounts)
con.register("Transactions", transactions)
return con.execute("""WITH
S AS (
SELECT DISTINCT
t.account_id,
DATE_FORMAT(day, '%Y-%m-01') AS day,
transaction_id AS tx,
SUM(amount) OVER (
PARTITION BY account_id, DATE_FORMAT(day, '%Y-%m-01')
) > max_income AS marked
FROM
Transactions AS t
LEFT JOIN Accounts AS a ON t.account_id = a.account_id
WHERE type = 'Creditor'
)
SELECT DISTINCT s1.account_id
FROM
S AS s1
LEFT JOIN S AS s2 ON s1.account_id = s2.account_id AND TIMESTAMPDIFF(Month, s1.day, s2.day) = 1
WHERE s1.marked = 1 AND s2.marked = 1
ORDER BY s1.tx;""").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.