Arrange Table by Gender — LeetCode 2308 Python Solution

MediumLeetCode PremiumDatabase
Problem
#2308
Reading time
4 min

Table schema

SQL
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

SQL
+-------------+---------+
| 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

Python
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

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

Related problems

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.

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