Sort the Students by Their Kth Score
You are given a 2D integer array score where score[i] represents student i's scores across j exams. Sort the students (rows) in descending order based on the kth column (0-indexed). Return the sorted array.
This is a straightforward custom sorting problem where we sort a 2D array by a specific column in descending order. Use the built-in sort with a comparator that compares the kth element of each row.
Time is O(n log n) for sorting n students, space O(1) if sorting in place. Edge cases include a single student (return unchanged), all students with the same kth score (stable order), and extreme values.
This problem demonstrates how sorting works on structured data with multiple fields per record. The comparator accesses the kth element of each row and returns the comparison result.
Sorting by a specific column is a fundamental data processing operation. The custom comparator approach generalizes to any number of columns and any sorting direction, making it a versatile tool for structured data manipulation. The row-based sorting approach ensures each student's scores remain together as a unit while being reordered by the kth exam score. This preserves data integrity during column-based sorting operations common in spreadsheet and database applications.Example Input & Output
Sort by column 0: 5 then 3.
Equal scores.
Sort by column 2: 11(row1) > 9(row0) > 3(row2).
Sort by column 1: 40 then 30 then 20.
Single student.
Algorithm Flow

Solution Approach
Sort rows using a custom comparator on the kth column in descending order.
Time O(n log n), Space O(1).
Best Answers
import java.util.*;
class Solution {
public int[][] solution(int[][] score, int k) {
Arrays.sort(score, (a,b) -> b[k] - a[k]);
return score;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
