Order Two Columns Independently
MediumUpdated: Aug 2, 2025
Practice on:
Problem
Table: Data
+-------------+------+
| Column Name | Type |
+-------------+------+
| first_col | int |
| second_col | int |
+-------------+------+
This table may contain duplicate rows.
Write a solution to independently:
- order
first_colin ascending order. - order
second_colin descending order.
The result format is in the following example.
Examples
Example 1:
Input:
Data table:
+-----------+------------+
| first_col | second_col |
+-----------+------------+
| 4 | 2 |
| 2 | 3 |
| 3 | 1 |
| 1 | 4 |
+-----------+------------+
Output:
+-----------+------------+
| first_col | second_col |
+-----------+------------+
| 1 | 4 |
| 2 | 3 |
| 3 | 2 |
| 4 | 1 |
+-----------+------------+
Solution
Method 1 – Independent Sorting and Row Construction
Intuition
We need to sort the first column in ascending order and the second column in descending order, then pair the sorted values row-wise. This is a classic independent column sort and zip problem.
Approach
- Select all values from
first_coland sort them in ascending order. - Select all values from
second_coland sort them in descending order. - Pair the sorted values row-wise to form the result.
Code
MySQL
SELECT
t1.first_col,
t2.second_col
FROM
(SELECT first_col, ROW_NUMBER() OVER (ORDER BY first_col ASC) AS rn FROM Data) t1
JOIN (SELECT second_col, ROW_NUMBER() OVER (ORDER BY second_col DESC) AS rn FROM Data) t2
ON t1.rn = t2.rn;
PostgreSQL
SELECT
t1.first_col,
t2.second_col
FROM
(SELECT first_col, ROW_NUMBER() OVER (ORDER BY first_col ASC) AS rn FROM Data) t1
JOIN (SELECT second_col, ROW_NUMBER() OVER (ORDER BY second_col DESC) AS rn FROM Data) t2
ON t1.rn = t2.rn;
Python (pandas)
class Solution:
def order_columns(self, data: 'pd.DataFrame') -> 'pd.DataFrame':
a = sorted(data['first_col'])
b = sorted(data['second_col'], reverse=True)
return pd.DataFrame({'first_col': a, 'second_col': b})
Complexity
- ⏰ Time complexity:
O(N log N), where N is the number of rows. Sorting each column independently is O(N log N). - 🧺 Space complexity:
O(N), for storing the sorted columns and the result.