MediumNo. 2159LeetCode Premium

Order Two Columns Independently — LeetCode 2159 Python Solution

Topics
Database
Reading time
4 min

Table schema

SQLTable schema
Table: Data +-------------+------+ | Column Name | Type | +-------------+------+ | first_col | int | | second_col | int | +-------------+------+ This table may contain duplicate rows. Write a solution to independently: order first_col in ascending order.

Example

SQLExample
+-------------+------+
| Column Name | Type |
+-------------+------+
| first_col   | int  |
| second_col  | int  |
+-------------+------+
This table may contain duplicate rows.

Python solution

PythonSolution
import duckdb
import pandas as pd

def solution(data: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Data", data)
    return con.execute("""WITH
    S AS (
        SELECT
            first_col,
            ROW_NUMBER() OVER (ORDER BY first_col) AS rk
        FROM Data
    ),
    T AS (
        SELECT
            second_col,
            ROW_NUMBER() OVER (ORDER BY second_col DESC) AS rk
        FROM Data
    )
SELECT first_col, second_col
FROM
    S
    JOIN T USING (rk);""").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 2159. Order Two Columns Independently?

LeetCode 2159. Order Two Columns Independently is rated Medium on LeetCode.

What topics does LeetCode 2159. Order Two Columns Independently cover?

LeetCode 2159. Order Two Columns Independently is tagged Database on LeetCode.

Is LeetCode 2159. Order Two Columns Independently a premium problem?

Yes. LeetCode 2159. Order Two Columns Independently 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.