We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Sort the Students by Their Kth Score

Number: 2631

Difficulty: Medium

Paid? No

Companies: IBM


Problem Description

Given an m x n integer matrix where each row represents a student's exam scores and each column a different exam, sort the students (i.e., rows) in descending order based on their kth exam score.


Key Insights

  • The kth score in each row is used as the key for sorting.
  • Since all scores are distinct, no tie-breaking is required.
  • Sorting in descending order can be efficiently achieved using built-in sort functions with a custom comparator or key.
  • The problem essentially reduces to sorting a list of arrays based on one of their elements.

Space and Time Complexity

Time Complexity: O(m log m), where m is the number of students. Space Complexity: O(m) (depending on the language’s sorting implementation).


Solution

The solution uses a sorting algorithm where each row (representing a student's exam scores) is compared based on its kth element. In Python, for example, we use the sort() function with a lambda function as the key to extract the kth element, sorting in reverse order for a descending result. Similar approaches are used in JavaScript (using Array.sort), C++ (using std::sort with a lambda comparator), and Java (using Arrays.sort with a custom comparator). The trick is to ensure the custom comparator correctly orders the elements in descending order based on the kth score.


Code Solutions

# Define a function to sort the score matrix by kth score in descending order.
def sort_the_students(score, k):
    # Using the built-in sort method with a lambda that specifies
    # the kth exam score as the key and reverse=True for descending order.
    score.sort(key=lambda student: student[k], reverse=True)
    return score

# Example usage:
score = [[10,6,9,1], [7,5,11,2], [4,8,3,15]]
k = 2
sorted_score = sort_the_students(score, k)
print(sorted_score)  # Expected output: [[7,5,11,2],[10,6,9,1],[4,8,3,15]]
← Back to All Questions