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_col
in ascending order. - order
second_col
in descending order.
The result format is in the following example.
Examples
Example 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_col
and sort them in ascending order. - Select all values from
second_col
and sort them in descending order. - Pair the sorted values row-wise to form the result.
Code
|
|
|
|
|
|
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.