Flag Account Takeovers: New Login Followed by a Large Transfer
SQL & DataAuto-graded · 15 test casesLast updated
Join logins, users and transfers to flag logins from a new device or IP that are followed within two hours by a large transfer to a first-time recipient.
Spot suspected account takeovers
A payments app wants to flag suspected account takeovers (ATO). You get three tables as lists of dictionaries: users, logins and transfers. Return one row for every successful login that looks like a takeover, along with the transfer that made it suspicious.
"Now" is fixed at 2025-09-01T00:00:00 (UTC). All timestamps are ISO-8601 strings without a time zone, for example "2025-08-25T10:10:00", and all are UTC.
Input
users: dictionaries withuser_id(int) andcreated_at(timestamp string).logins: dictionaries withuser_id,ts(timestamp string),ip(string),device_id(string) andsuccess(bool).transfers: dictionaries withtx_id(int),sender_id(int),recipient_id(int),ts(timestamp string),amount_usd(decimal amount as a string such as"650.00") andstatus("completed"or"reversed").
What counts as a flagged login
A login record is flagged when all of the following hold.
- Eligible login. It is successful, and its timestamp
login_tssatisfies2025-08-25T00:00:00 <= login_ts < 2025-09-01T00:00:00. The user must also exist inusers. - Account age.
login_ts - created_atis at least 7 days. Logins from accounts younger than 7 days are ignored. - Novelty. Look at that user's successful logins whose timestamps lie strictly between
login_ts - 30 daysandlogin_ts, with both ends excluded. Call this the lookback set.- The login has a new device if no login in the lookback set has the same
device_id. - The login has a new IP if no login in the lookback set has the same
ip. - The login must have a new device, a new IP, or both.
- The login has a new device if no login in the lookback set has the same
- Suspicious transfer. Only transfers with status
"completed"are considered, both as candidates and as history. There must be at least one transfer that satisfies all of these:sender_idequals the login's user.login_ts < tx_ts <= login_ts + 2 hours(the start is excluded, the end is included).amount_usdis strictly greater than 500.- The recipient is a first-time recipient: no completed transfer exists from the same sender to the same recipient with a timestamp strictly earlier than
tx_ts.
If several transfers qualify for one login, keep only the one with the smallest (tx_ts, tx_id). Only transfers that already passed every check above compete for this.
Each qualifying login record produces exactly one output row. Two different logins may point to the same transfer, and both rows are kept.
Output
Return a list of dictionaries with exactly these keys:
user_idlogin_ts: the login's original stringdevice_idipreason_code:"BOTH"if the device and IP are both new,"NEW_DEVICE"if only the device is new,"NEW_IP"if only the IP is newtx_idtx_ts: the transfer's original stringamount_usd: the transfer's original value, unchangedfirst_time_recipient_flag: alwaysTrue
Sort the rows by login_ts (as a time), then user_id, then tx_ts, then tx_id, all ascending. Return an empty list if nothing qualifies.
Constraints
- Use the fixed "now" and window above. Do not read the system clock.
- Compare
amount_usdas an exact decimal, not a float. - Failed logins never count as history and are never flagged.
- Reversed transfers are ignored completely.
- Input sizes are small enough for a straightforward solution, but grouping by user keeps it fast.
Examples
Example 1
Input: flag_account_takeover([{'user_id': 1, 'created_at': '2025-07-01T10:00:00'}, {'user_id': 2, 'created_at': '2025-08-28T09:00:00'}, {'user_id': 3, 'created_at': '2025-05-15T12:00:00'}, {'user_id': 4, 'created_at': '2025-08-01T08:30:00'}], [{'user_id': 1, 'ts': '2025-08-20T09:00:00', 'ip': '1.1.1.1', 'device_id': 'A', 'success': True}, {'user_id': 1, 'ts': '2025-08-25T10:10:00', 'ip': '2.2.2.2', 'device_id': 'B', 'success': True}, {'user_id': 1, 'ts': '2025-08-25T10:40:00', 'ip': '2.2.2.2', 'device_id': 'B', 'success': True}, {'user_id': 2, 'ts': '2025-08-29T21:00:00', 'ip': '3.3.3.3', 'device_id': 'C', 'success': True}, {'user_id': 2, 'ts': '2025-08-30T01:00:00', 'ip': '4.4.4.4', 'device_id': 'C', 'success': True}, {'user_id': 3, 'ts': '2025-08-31T15:00:00', 'ip': '5.5.5.5', 'device_id': 'D', 'success': True}, {'user_id': 3, 'ts': '2025-08-31T16:30:00', 'ip': '5.5.5.5', 'device_id': 'E', 'success': True}, {'user_id': 4, 'ts': '2025-09-01T00:10:00', 'ip': '6.6.6.6', 'device_id': 'F', 'success': False}], [{'tx_id': 101, 'sender_id': 1, 'recipient_id': 9, 'ts': '2025-08-25T11:15:00', 'amount_usd': '650.00', 'status': 'completed'}, {'tx_id': 102, 'sender_id': 1, 'recipient_id': 9, 'ts': '2025-08-26T09:00:00', 'amount_usd': '50.00', 'status': 'completed'}, {'tx_id': 103, 'sender_id': 2, 'recipient_id': 8, 'ts': '2025-08-30T01:45:00', 'amount_usd': '800.00', 'status': 'completed'}, {'tx_id': 104, 'sender_id': 2, 'recipient_id': 7, 'ts': '2025-08-27T10:00:00', 'amount_usd': '20.00', 'status': 'completed'}, {'tx_id': 105, 'sender_id': 3, 'recipient_id': 6, 'ts': '2025-08-31T16:45:00', 'amount_usd': '700.00', 'status': 'completed'}, {'tx_id': 106, 'sender_id': 3, 'recipient_id': 6, 'ts': '2025-09-01T01:00:00', 'amount_usd': '10.00', 'status': 'reversed'}, {'tx_id': 107, 'sender_id': 3, 'recipient_id': 5, 'ts': '2025-08-10T08:00:00', 'amount_usd': '5.00', 'status': 'completed'}, {'tx_id': 108, 'sender_id': 4, 'recipient_id': 5, 'ts': '2025-09-01T00:20:00', 'amount_usd': '900.00', 'status': 'completed'}])
Output: [{'user_id': 1, 'login_ts': '2025-08-25T10:10:00', 'device_id': 'B', 'ip': '2.2.2.2', 'reason_code': 'BOTH', 'tx_id': 101, 'tx_ts': '2025-08-25T11:15:00', 'amount_usd': '650.00', 'first_time_recipient_flag': True}, {'user_id': 3, 'login_ts': '2025-08-31T15:00:00', 'device_id': 'D', 'ip': '5.5.5.5', 'reason_code': 'BOTH', 'tx_id': 105, 'tx_ts': '2025-08-31T16:45:00', 'amount_usd': '700.00', 'first_time_recipient_flag': True}, {'user_id': 3, 'login_ts': '2025-08-31T16:30:00', 'device_id': 'E', 'ip': '5.5.5.5', 'reason_code': 'NEW_DEVICE', 'tx_id': 105, 'tx_ts': '2025-08-31T16:45:00', 'amount_usd': '700.00', 'first_time_recipient_flag': True}]
Hints
Hint 1
Group successful logins and completed transfers by user first, so that each login only has to scan its own user's records.
Hint 2
For the novelty test, collect the user's successful logins in the open interval (login_ts - 30 days, login_ts), then check separately whether the device and the IP appear in that set.
Hint 3
Apply the first-time-recipient filter before choosing the earliest transfer, then pick the minimum by (tx_ts, tx_id). Compare amounts with Decimal and keep the original strings for output.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the task as a pipeline of narrow filters applied to each login record.
-
Index the data. Group successful logins by user and completed transfers by sender. Parse timestamps once and convert amounts to
Decimal, so each login only looks at its own user's records. -
Filter eligible logins. Keep a login only if it falls in
[2025-08-25, 2025-09-01), the user exists, and the account is at least 7 days old at login time. -
Test novelty. Build the lookback set of the same user's successful logins in the open interval
(login_ts - 30d, login_ts).- The device is new if no lookback login has that
device_id. - The IP is new if no lookback login has that
ip. - Skip the login unless at least one of them is new.
A login from a new device is automatically the user's first login from it in the last 30 days. Later logins from the same device see the earlier one in their lookback, so no extra "first" logic is needed.
- The device is new if no lookback login has that
-
Find candidate transfers. Among the sender's completed transfers, keep those with
amount > 500andlogin_ts < tx_ts <= login_ts + 2h. Then keep only those whose recipient has no earlier completed transfer from the same sender (p_ts < tx_ts). -
Pick the earliest. Choose the candidate with the smallest
(tx_ts, tx_id). Because the first-time check happens before this choice, "earliest" means the earliest qualifying transfer. -
Emit and sort. Build the output row with the reason code, then sort by login time, user, transfer time and transfer id.
Why it is correct
- Each condition is checked exactly as defined, including the boundary rules. The window and lookback are half-open or open as specified, the 2-hour end is inclusive, and the amount comparison is a strict
>on exact decimals. - Reversed transfers and failed logins are filtered out up front, so they cannot affect history or candidates.
- One row is produced per qualifying login. Two logins that share a transfer, such as the two user-3 logins in the sample, each yield a row, and they are not duplicates of each other.
- Sorting on parsed datetimes rather than strings gives a deterministic order.
Complexity
Let L_u be the number of successful logins and T_u the number of completed transfers for a user. For each eligible login, the solution scans the lookback (O(L_u)) and the candidate transfers with their history checks (O(T_u^2) in the worst case). The total is the sum over users of L_u * (L_u + T_u^2), which is small for per-user data, plus O(R log R) for sorting the R output rows. Space is O(L + T).
Reference solution
from collections import defaultdict
from datetime import datetime, timedelta
from decimal import Decimal
from typing import Dict, List
def _parse(value):
return datetime.fromisoformat(value.replace("Z", "+00:00"))
def flag_account_takeover(users: List[Dict], logins: List[Dict], transfers: List[Dict]) -> List[Dict]:
win_start = datetime.fromisoformat("2025-08-25T00:00:00")
win_end = datetime.fromisoformat("2025-09-01T00:00:00")
created = {u["user_id"]: _parse(u["created_at"]) for u in users}
# successful logins grouped by user: (ts, ip, device_id, raw_ts)
logins_by_user = defaultdict(list)
for l in logins:
if l["success"]:
logins_by_user[l["user_id"]].append((_parse(l["ts"]), l["ip"], l["device_id"], l["ts"]))
# completed transfers grouped by sender
transfers_by_sender = defaultdict(list)
for t in transfers:
if t["status"] == "completed":
transfers_by_sender[t["sender_id"]].append(
(_parse(t["ts"]), t["tx_id"], t["recipient_id"], Decimal(str(t["amount_usd"])), t)
)
result = []
for uid, user_logins in logins_by_user.items():
if uid not in created:
continue
sent = transfers_by_sender.get(uid, [])
for ts, ip, device, raw_ts in user_logins:
if not (win_start <= ts < win_end):
continue
if ts - created[uid] < timedelta(days=7):
continue
lookback = [
(h_ip, h_dev)
for h_ts, h_ip, h_dev, _ in user_logins
if ts - timedelta(days=30) < h_ts < ts
]
new_device = not any(h_dev == device for _, h_dev in lookback)
new_ip = not any(h_ip == ip for h_ip, _ in lookback)
if not (new_device or new_ip):
continue
candidates = []
for tx_ts, tx_id, recipient, amount, raw in sent:
if amount <= Decimal("500"):
continue
if not (ts < tx_ts <= ts + timedelta(hours=2)):
continue
seen_before = any(
p_rec == recipient and p_ts < tx_ts
for p_ts, _, p_rec, _, _ in sent
)
if not seen_before:
candidates.append((tx_ts, tx_id, raw))
if not candidates:
continue
tx_ts, tx_id, raw = min(candidates, key=lambda c: (c[0], c[1]))
if new_device and new_ip:
reason = "BOTH"
elif new_device:
reason = "NEW_DEVICE"
else:
reason = "NEW_IP"
result.append({
"user_id": uid,
"login_ts": raw_ts,
"device_id": device,
"ip": ip,
"reason_code": reason,
"tx_id": tx_id,
"tx_ts": raw["ts"],
"amount_usd": raw["amount_usd"],
"first_time_recipient_flag": True,
})
result.sort(key=lambda r: (_parse(r["login_ts"]), r["user_id"], _parse(r["tx_ts"]), r["tx_id"]))
return result