Number of Accounts That Did Not Stream — LeetCode 2020 Python Solution

MediumLeetCode PremiumDatabase
Problem
#2020
Reading time
3 min

Table schema

SQL
Table: Subscriptions +-------------+------+ | Column Name | Type | +-------------+------+ | account_id | int | | start_date | date | | end_date | date | +-------------+------+ account_id is the primary key column for this table. Each row of this table indicates the start and end dates of an account's subscription.

Example

SQL
+-------------+------+
| Column Name | Type |
+-------------+------+
| account_id  | int  |
| start_date  | date |
| end_date    | date |
+-------------+------+
account_id is the primary key column for this table.
Each row of this table indicates the start and end dates of an account's subscription.
Note that always start_date < end_date.

Python solution

Python
import duckdb
import pandas as pd

def solution(subscriptions: pd.DataFrame, streams: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Subscriptions", subscriptions)
    con.register("Streams", streams)
    return con.execute("""SELECT COUNT(sub.account_id) AS accounts_count
FROM
    Subscriptions AS sub
    LEFT JOIN Streams USING (account_id)
WHERE
    YEAR(start_date) <= 2021
    AND YEAR(end_date) >= 2021
    AND (YEAR(stream_date) != 2021 OR stream_date > end_date);""").df()

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 2020. Number of Accounts That Did Not Stream?
LeetCode 2020. Number of Accounts That Did Not Stream is rated Medium on LeetCode.
What topics does LeetCode 2020. Number of Accounts That Did Not Stream cover?
LeetCode 2020. Number of Accounts That Did Not Stream is tagged Database on LeetCode.
Is LeetCode 2020. Number of Accounts That Did Not Stream a premium problem?
Yes. LeetCode 2020. Number of Accounts That Did Not Stream 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