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 Their Kth Score (k=1)Input Matrix:Student 1: [10, 6, 9, 1]Student 2: [7, 5, 11, 2]Student 3: [4, 8, 3, 15]k=1Column k scores: [6, 5, 8]Sort by k-th columnOutput Matrix:Student 3: [4, 8, 3, 15]Student 1: [10, 6, 9, 1]Student 2: [7, 5, 11, 2]k=1Sorted: [8, 6, 5]Rows reordered by k-th column values (descending)Student 3 (score 8) → Student 1 (score 6) → Student 2 (score 5)
Understanding the Visualization
1
Input Matrix
Each row represents a student, each column an exam
2
Focus on Column k
Extract k-th exam scores to determine sort order
3
Sort Rows
Reorder entire rows based on k-th column values (highest to lowest)
Key Takeaway
🎯 Key Insight: Sort entire rows as units based on a single column's values, maintaining row integrity while reordering by performance
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