MediumNo. 2308LeetCode Premium
Arrange Table by Gender — LeetCode 2308 Python Solution
- Topics
- Database
- Reading time
- 4 min
- Source
- leetcode.com
Table schema
Table: Genders +-------------+---------+ | Column Name | Type | +-------------+---------+ | user_id | int | | gender | varchar | +-------------+---------+ user_id is the primary key (column with unique values) for this table. gender is ENUM (category) of type 'female', 'male', or 'other'.Example
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| user_id | int |
| gender | varchar |
+-------------+---------+
user_id is the primary key (column with unique values) for this table.
gender is ENUM (category) of type 'female', 'male', or 'other'.
Each row in this table contains the ID of a user and their gender.
The table has an equal number of 'female', 'male', and 'other'.Python solution
import duckdb
import pandas as pd
def solution(genders: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Genders", genders)
return con.execute("""WITH
t AS (
SELECT
*,
RANK() OVER (
PARTITION BY gender
ORDER BY user_id
) AS rk1,
CASE
WHEN gender = 'female' THEN 0
WHEN gender = 'other' THEN 1
ELSE 2
END AS rk2
FROM Genders
)
SELECT user_id, gender
FROM t
ORDER BY rk1, rk2;""").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 2308. Arrange Table by Gender?
LeetCode 2308. Arrange Table by Gender is rated Medium on LeetCode.
- What topics does LeetCode 2308. Arrange Table by Gender cover?
LeetCode 2308. Arrange Table by Gender is tagged Database on LeetCode.
- Is LeetCode 2308. Arrange Table by Gender a premium problem?
Yes. LeetCode 2308. Arrange Table by Gender is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.