Unique Orders and Customers Per Month — LeetCode 1565 Python Solution

EasyLeetCode PremiumDatabase
Problem
#1565
Reading time
3 min

Table schema

SQL
Table: Orders +---------------+---------+ | Column Name | Type | +---------------+---------+ | order_id | int | | order_date | date | | customer_id | int | | invoice | int | +---------------+---------+ order_id is the column with unique values for this table. This table contains information about the orders made by customer_id.

Example

SQL
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| order_id      | int     |
| order_date    | date    |
| customer_id   | int     |
| invoice       | int     |
+---------------+---------+
order_id is the column with unique values for this table.
This table contains information about the orders made by customer_id.

Python solution

Python
import pandas as pd


def unique_orders_and_customers(orders: pd.DataFrame) -> pd.DataFrame:
    filtered_orders = orders[orders["invoice"] > 20]
    filtered_orders["month"] = (
        filtered_orders["order_date"].dt.to_period("M").astype(str)
    )
    result = (
        filtered_orders.groupby("month")
        .agg(
            order_count=("order_id", "count"), customer_count=("customer_id", "nunique")
        )
        .reset_index()
    )
    return result

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 1565. Unique Orders and Customers Per Month?
LeetCode 1565. Unique Orders and Customers Per Month is rated Easy on LeetCode.
What topics does LeetCode 1565. Unique Orders and Customers Per Month cover?
LeetCode 1565. Unique Orders and Customers Per Month is tagged Database on LeetCode.
Is LeetCode 1565. Unique Orders and Customers Per Month a premium problem?
Yes. LeetCode 1565. Unique Orders and Customers Per Month 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