Magicsheet logo

Sort the Students by Their Kth Score

Medium
71.7%
Updated 6/1/2025

Asked by 3 Companies

Sort the Students by Their Kth Score

What is this problem about?

"Sort the Students by Their Kth Score" is a matrix-based sorting problem. You are given a 2D integer matrix where each row represents a student and each column represents a specific exam score. You are also given an integer kk.

Your task is to sort the entire rows of the matrix in descending order based on the values in the kk-th column (the kk-th exam). This is a practical example of record sorting, where you reorder a collection of objects (students) based on a specific attribute (one of their exam scores).

Why is this asked in interviews?

Companies like IBM and Amazon ask this interview question to test a candidate's ability to perform custom sorting on complex data structures. It evaluates whether you can manipulate 2D arrays (matrices) and whether you understand how to use custom comparators in your programming language. It’s a common task in data engineering and backend development, where you often need to sort records based on a user-selected field.

Algorithmic pattern used

The primary algorithmic pattern is Custom Sorting.

  1. Access the kk-th column for each row.
  2. Define a comparison rule that compares two rows based on the value at index kk.
  3. Sort the matrix rows using this rule in descending order. Most modern programming languages allow you to pass a key or a comparator to the built-in sort function, making this an O(MlogM)O(M \log M) operation, where MM is the number of rows.

Example explanation

Matrix: [[10, 6, 9, 1], [7, 5, 11, 2], [4, 8, 3, 15]] k = 2 (the 3rd exam, 0-indexed).

  • Scores at index 2: [9, 11, 3].
  • Sorting these in descending order: 11 (row 1), 9 (row 0), 3 (row 2). Result: [[7, 5, 11, 2], [10, 6, 9, 1], [4, 8, 3, 15]]

Common mistakes candidates make

One frequent mistake is sorting the columns instead of the rows, which garbles the student data. Another mistake is sorting in ascending order instead of the requested descending order. Some candidates also try to manually implement a sorting algorithm like Bubble Sort, which is inefficient (O(M2)O(M^2)) and unnecessary when high-performance built-in sorting utilities are available.

Interview preparation tip

To master the "Sort the Students by Their Kth Score coding problem," practice using lambda functions or anonymous comparators. In Python, matrix.sort(key=lambda x: x[k], reverse=True) is the most idiomatic way. In Java, you would use Arrays.sort(matrix, (a, b) -> b[k] - a[k]). Being comfortable with these one-liners shows you have a strong grasp of the language's utility functions.

Similar Questions