MediumNo. 2308LeetCode Premium

Arrange Table by Gender — LeetCode 2308 Python Solution

Topics
Database
Reading time
4 min

Table schema

SQLTable 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

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

PythonSolution
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

Related problems
No.ProblemDifficulty
0175Combine Two TablesEasy
0176Second Highest SalaryMedium
0177Nth Highest SalaryMedium
0178Rank ScoresMedium
0180Consecutive NumbersMedium
0181Employees Earning More Than Their ManagersEasy

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.

Free to download. Check it runs on your machine, then pick a plan.