#2545

Sort the Students by Their Kth Score

Medium
ArraySortingMatrixSortingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(m log m)
O(m log m)
Space
O(m)
O(1)
💡

Intuition

Time O(m log m)Space O(1)

The optimal approach leverages Python's built-in sorting capabilities to sort the students directly based on the k-th score, which is efficient and concise.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use the built-in sort function to sort the matrix based on the k-th column.
  2. 2Step 2: Specify the sorting order as descending.
  3. 3Step 3: Return the sorted matrix.
solution.py4 lines
1score = [[10,6,9,1],[7,5,11,2],[4,8,3,15]]
2k = 2
3sorted_score = sorted(score, key=lambda x: x[k], reverse=True)
4print(sorted_score)

Complexity note: The complexity remains O(m log m) due to sorting, but we do not create an additional copy of the matrix, making the space complexity O(1).

  • 1Sorting is a common operation in many problems; understanding how to leverage built-in functions can save time.
  • 2Distinct integers in the matrix simplify the sorting process as there are no ties.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.