Sort the Students by Their Kth Score - Problem

Imagine you're a teacher managing exam results for your class. You have m students who took n different exams, and you want to rank them based on their performance in one specific exam.

You're given a score matrix where each row represents a student and score[i][j] is the score that student i got on exam j. All scores are unique integers.

Given an integer k, you need to sort the students (rearrange the rows) based on their scores in the k-th exam from highest to lowest.

Goal: Return the matrix with rows sorted by the k-th column in descending order.

Input & Output

example_1.py โ€” Basic Case
$ Input: score = [[10,6,9,1],[7,5,11,2],[4,8,3,15]], k = 2
โ€บ Output: [[7,5,11,2],[10,6,9,1],[4,8,3,15]]
๐Ÿ’ก Note: Sorting by k=2 (3rd exam): scores are [9,11,3]. Student with score 11 goes first, then 9, then 3.
example_2.py โ€” Single Student
$ Input: score = [[3,4]], k = 0
โ€บ Output: [[3,4]]
๐Ÿ’ก Note: With only one student, the matrix remains unchanged regardless of which exam we sort by.
example_3.py โ€” Already Sorted
$ Input: score = [[5,4,3],[2,1,0]], k = 0
โ€บ Output: [[5,4,3],[2,1,0]]
๐Ÿ’ก Note: Students are already sorted by exam 0 in descending order (5 > 2), so no change needed.

Visualization

Tap to expand
Student Ranking by K-th Exam ScoreBefore Sorting (k=1):859278Student A769589Student B887391Student CAfter Sorting:769589Student B859278Student A887391Student CSorting Process1. Compare k-th column: 95 > 92 > 732. Rearrange entire rows in descending orderRed border: k-th column (exam to sort by) | Green border: Final sorted result
Understanding the Visualization
1
Identify Target Column
Focus on the k-th exam column that determines the ranking
2
Compare Scores
Use custom comparator to compare students by their k-th exam score
3
Rearrange Rows
Sort the entire rows (students) based on k-th column values
4
Final Ranking
Students are now ordered from highest to lowest k-th exam score
Key Takeaway
๐ŸŽฏ Key Insight: We don't need to sort individual elements - we sort entire rows (students) based on one column (exam score), treating each student as a single unit with a comparison key.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(m log m)

Built-in sorting algorithms are typically O(m log m) where m is number of students

n
2n
โšก Linearithmic
Space Complexity
O(1) to O(m)

Space complexity depends on sorting algorithm used (QuickSort is O(log m), MergeSort is O(m))

n
2n
โœ“ Linear Space

Constraints

  • m == score.length
  • n == score[i].length
  • 1 โ‰ค m, n โ‰ค 250
  • 1 โ‰ค score[i][j] โ‰ค 105
  • score consists of distinct integers
  • 0 โ‰ค k < n
Asked in
Amazon 12 Google 8 Microsoft 6 Meta 4
24.7K Views
Medium Frequency
~8 min Avg. Time
892 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