Order Two Columns Independently — LeetCode 2159 Python Solution

MediumLeetCode PremiumDatabase
Problem
#2159
Reading time
4 min

Table schema

SQL
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

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

Python solution

Python
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

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

Related problems

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.

Get Stealth Interview