Sort the Students by Their Kth Score - 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 i-th student got in the j-th 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 k-th (0-indexed) exam from the highest to the lowest.

Return the matrix after sorting it.

Input & Output

Example 1 — Basic Case
$ Input: score = [[10,6,9,1],[7,5,11,2],[4,8,3,15]], k = 1
Output: [[4,8,3,15],[10,6,9,1],[7,5,11,2]]
💡 Note: Sort by column k=1 (2nd column): Student scores in column 1 are [6,5,8]. Sorted descending: 8 > 6 > 5, so rows reorder to [[4,8,3,15],[10,6,9,1],[7,5,11,2]]
Example 2 — Sort by First Column
$ Input: score = [[3,4],[5,6]], k = 0
Output: [[5,6],[3,4]]
💡 Note: Sort by column k=0 (1st column): Student scores in column 0 are [3,5]. Sorted descending: 5 > 3, so rows reorder to [[5,6],[3,4]]
Example 3 — Single Student
$ Input: score = [[1,2,3]], k = 2
Output: [[1,2,3]]
💡 Note: Only one student, so the matrix remains unchanged regardless of which column k we sort by

Constraints

  • m == score.length
  • n == score[i].length
  • 2 ≤ n ≤ 1000
  • 1 ≤ m ≤ 1000
  • 1 ≤ score[i][j] ≤ 106
  • score consists of distinct integers
  • 0 ≤ k < n

Visualization

Tap to expand
Sort Students by Kth Score INPUT Score Matrix (m=3, n=4) j=0 j=1 j=2 j=3 i=0 10 6 9 1 i=1 7 5 11 2 i=2 4 8 3 15 k = 1 (Column to sort by) Values at k=1: 6 5 8 Input: score = [[10,6,9,1], [7,5,11,2],[4,8,3,15]] k = 1 ALGORITHM STEPS 1 Identify Sort Key Extract column k=1 values [6, 5, 8] 2 Define Comparator Compare rows by score[row][k] Sort descending (high to low) 3 Sort Comparisons 8 > 6 > 5 (descending) 8 --> 1st 6 --> 2nd 5 --> 3rd 4 Reorder Rows Row2 --> Row0 --> Row1 Maintain entire row data FINAL RESULT Sorted Matrix (by k=1 desc) j=0 j=1 j=2 j=3 4 8 3 15 max 10 6 9 1 mid 7 5 11 2 min Row Mapping: Original Sorted Row 2 --> Row 0 Row 0 --> Row 1 Row 1 --> Row 2 Output: [[4,8,3,15], [10,6,9,1], [7,5,11,2]] Key Insight: Use built-in sort with a custom comparator that compares rows based on their k-th element. Time: O(m log m) for sorting m rows. Space: O(1) if in-place sort is used. TutorialsPoint - Sort the Students by Their Kth Score | Built-in Sort with Custom Comparator
Asked in
Google 25 Amazon 20 Microsoft 15
32.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen