Problem
There is a class with m students and n exams. You are given a
0-indexed m x n integer matrix score, where each row represents one student and score[i][j] denotes the score the ith student got in the jth
exam. The matrix score contains distinct integers only.
You are also given an integer k. Sort the students (i.e., the rows of the matrix) by their scores in the kth (0-indexed) exam from the highest to the lowest.
Return the matrix after sorting it.
Examples
Example 1
| |
Example 2
| |
Constraints
m == score.lengthn == score[i].length1 <= m, n <= 2501 <= score[i][j] <= 10^5scoreconsists of distinct integers.0 <= k < n
Solution
Method 1 - Custom Comparator Sorting
Intuition
We need to sort the matrix rows based on the kth column values in descending order (highest to lowest). Each row represents a student, and we want to reorder students by their performance in the kth exam.
Approach
- Use a custom comparator that compares rows based on the kth column value
- Sort in descending order since we want highest scores first
- The sorting will rearrange entire rows, preserving each student’s complete score profile
Code
| |
| |
| |
| |
| |
| |
| |
Complexity
- ⏰ Time complexity:
O(m log m)where m is the number of students (rows) - 🧺 Space complexity:
O(1)if sorting in-place,O(m)for the sorting algorithm’s internal space