Code Logo

Sort the Students by Their Kth Score

Published at24 Jul 2026
Easy 0 views
Like0

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

Example 1
Input
[[3,4],[5,6]], 0
Output
[[5,6],[3,4]]
Explanation

Sort by column 0: 5 then 3.

Example 2
Input
[[5,5],[5,5]], 0
Output
[[5,5],[5,5]]
Explanation

Equal scores.

Example 3
Input
[[10,6,9,1],[7,5,11,2],[4,8,3,15]], 2
Output
[[7,5,11,2],[10,6,9,1],[4,8,3,15]]
Explanation

Sort by column 2: 11(row1) > 9(row0) > 3(row2).

Example 4
Input
[[10,20],[30,40],[20,30]], 1
Output
[[30,40],[20,30],[10,20]]
Explanation

Sort by column 1: 40 then 30 then 20.

Example 5
Input
[[1]], 0
Output
[[1]]
Explanation

Single student.

Algorithm Flow

Recommendation Algorithm Flow for Sort the Students by Their Kth Score
Recommendation Algorithm Flow for Sort the Students by Their Kth Score

Solution Approach

Sort rows using a custom comparator on the kth column in descending order.

function solution(score, k) {
  score.sort(function(a, b) { return b[k] - a[k]; });
  return score;
}

Time O(n log n), Space O(1).

Best Answers

java
import java.util.*;
class Solution {
    public int[][] solution(int[][] score, int k) {
        Arrays.sort(score, (a,b) -> b[k] - a[k]);
        return score;
    }
}