Orders With Maximum Quantity Above Average — LeetCode 1867 Python Solution

MediumLeetCode PremiumDatabase
Problem
#1867
Reading time
4 min

Table schema

SQL
Table: OrdersDetails +-------------+------+ | Column Name | Type | +-------------+------+ | order_id | int | | product_id | int | | quantity | int | +-------------+------+ (order_id, product_id) is the primary key (combination of columns with unique values) for this table. A single order is represented as multiple rows, one row for each product in the order.

Example

SQL
+-------------+------+
| Column Name | Type |
+-------------+------+
| order_id    | int  |
| product_id  | int  |
| quantity    | int  |
+-------------+------+
(order_id, product_id) is the primary key (combination of columns with unique values) for this table.
A single order is represented as multiple rows, one row for each product in the order.
Each row of this table contains the quantity ordered of the product product_id in the order order_id.

Python solution

Python
import duckdb
import pandas as pd

def solution(orders_details: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("OrdersDetails", orders_details)
    return con.execute("""WITH
    t AS (
        SELECT
            order_id,
            MAX(quantity) AS max_quantity,
            SUM(quantity) / COUNT(1) AS avg_quantity
        FROM OrdersDetails
        GROUP BY order_id
    )
SELECT order_id
FROM t
WHERE max_quantity > (SELECT MAX(avg_quantity) FROM t);""").df()

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 1867. Orders With Maximum Quantity Above Average?
LeetCode 1867. Orders With Maximum Quantity Above Average is rated Medium on LeetCode.
What topics does LeetCode 1867. Orders With Maximum Quantity Above Average cover?
LeetCode 1867. Orders With Maximum Quantity Above Average is tagged Database on LeetCode.
Is LeetCode 1867. Orders With Maximum Quantity Above Average a premium problem?
Yes. LeetCode 1867. Orders With Maximum Quantity Above Average 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