HardNo. 2991LeetCode Premium
Top Three Wineries — LeetCode 2991 Python Solution
- Topics
- Database
- Reading time
- 5 min
- Source
- leetcode.com
Table schema
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
+-------------+----------+
| 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
- Time
- O(n log n)(typical)
- Space · auxiliary
- O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0175 | Combine Two Tables | Easy |
| 0176 | Second Highest Salary | Medium |
| 0177 | Nth Highest Salary | Medium |
| 0178 | Rank Scores | Medium |
| 0180 | Consecutive Numbers | Medium |
| 0181 | Employees Earning More Than Their Managers | Easy |
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.