Leetcode #2991: Top Three Wineries
In this guide, we solve Leetcode #2991 **Top Three Wineries ** in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: Yes
- Tags: Database
Intuition
The task is relational in nature, which maps cleanly to DataFrame operations in Python.
By treating tables as DataFrames, joins and group-bys become concise and readable.
Approach
Load the inputs as DataFrames and apply the appropriate merge, filter, or group-by.
Select or rename the columns to match the required output.
Steps:
- Load inputs as DataFrames.
- Apply merge/groupby/filter operations.
- Select the output columns.
Example
+-------------+----------+
| 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
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
The time complexity is O(n log n) (typical). The space complexity is O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.