Top Three Wineries — LeetCode 2991 Python Solution

HardLeetCode PremiumDatabase
Problem
#2991
Reading time
5 min

Table schema

SQL
Table: Wineries +-------------+----------+ | Column Name | Type | +-------------+----------+ | id | int | | country | varchar | | points | int | | winery | varchar | +-------------+----------+ id is column of unique values for this table. This table contains id, country, points, and winery.

Example

SQL
+-------------+----------+
| Column Name | Type     |
+-------------+----------+
| id          | int      |
| country     | varchar  |
| points      | int      |
| winery      | varchar  |
+-------------+----------+
id is column of unique values for this table.
This table contains id, country, points, and winery.

Python solution

Python
import duckdb
import pandas as pd

def solution(wineries: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Wineries", wineries)
    return con.execute("""WITH
    T AS (
        SELECT
            country,
            CONCAT(winery, ' (', points, ')') AS winery,
            RANK() OVER (
                PARTITION BY country
                ORDER BY points DESC, winery
            ) AS rk
        FROM (SELECT country, SUM(points) AS points, winery FROM Wineries GROUP BY 1, 3) AS t
    )
SELECT
    t1.country,
    t1.winery AS top_winery,
    IFNULL(t2.winery, 'No second winery') AS second_winery,
    IFNULL(t3.winery, 'No third winery') AS third_winery
FROM
    T AS t1
    LEFT JOIN T AS t2 ON t1.country = t2.country AND t1.rk = t2.rk - 1
    LEFT JOIN T AS t3 ON t2.country = t3.country AND t2.rk = t3.rk - 1
WHERE t1.rk = 1
ORDER BY 1;""").df()

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 2991. Top Three Wineries?
LeetCode 2991. Top Three Wineries is rated Hard on LeetCode.
What topics does LeetCode 2991. Top Three Wineries cover?
LeetCode 2991. Top Three Wineries is tagged Database on LeetCode.
Is LeetCode 2991. Top Three Wineries a premium problem?
Yes. LeetCode 2991. Top Three Wineries 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