Sorting, and why the numbers are distinct!

The description of problems always brings important information - it is rare that an information inside the problem description doesn't add any value. For instance, in this problem all the scores are unique. This is done so that you can create a unique mapping score --> row which can be used to reconstruct the matrix after the sorting is completed. Hence you can complete the task in O(row*col + row*log(row))-time and O(row*col)-space. Code is down below, cheers, ACC.


There is a class with m students and n exams. You are given a 0-indexed m x n integer matrix score, where each row represents one student and score[i][j] denotes the score the ith student got in the jth exam. The matrix score contains distinct integers only.

You are also given an integer k. Sort the students (i.e., the rows of the matrix) by their scores in the kth (0-indexed) exam from the highest to the lowest.

Return the matrix after sorting it.

 

Example 1:

Input: score = [[10,6,9,1],[7,5,11,2],[4,8,3,15]], k = 2
Output: [[7,5,11,2],[10,6,9,1],[4,8,3,15]]
Explanation: In the above diagram, S denotes the student, while E denotes the exam.
- The student with index 1 scored 11 in exam 2, which is the highest score, so they got first place.
- The student with index 0 scored 9 in exam 2, which is the second highest score, so they got second place.
- The student with index 2 scored 3 in exam 2, which is the lowest score, so they got third place.

Example 2:

Input: score = [[3,4],[5,6]], k = 0
Output: [[5,6],[3,4]]
Explanation: In the above diagram, S denotes the student, while E denotes the exam.
- The student with index 1 scored 5 in exam 0, which is the highest score, so they got first place.
- The student with index 0 scored 3 in exam 0, which is the lowest score, so they got second place.

 

Constraints:

  • m == score.length
  • n == score[i].length
  • 1 <= m, n <= 250
  • 1 <= score[i][j] <= 105
  • score consists of distinct integers.
  • 0 <= k < n

public int[][] SortTheStudents(int[][] score, int k)
{
    int[][] retVal = new int[score.Length][];
    Hashtable htScoreToRow = new Hashtable();
    int[] kScores = new int[score.Length];

    for (int r = 0; r < score.Length; r++)
    {
        htScoreToRow.Add(score[r][k], r);
        kScores[r] = score[r][k];
        retVal[r] = new int[score[r].Length];
    }

    Array.Sort(kScores);

    for (int r = 0; r < kScores.Length; r++)
    {
        int row = (int)htScoreToRow[kScores[kScores.Length - r - 1]];
        for (int c = 0; c < score[r].Length; c++)
        {
            retVal[r][c] = score[row][c];
        }
    }

    return retVal;
}

Comments

Popular posts from this blog

Changing the root of a binary tree

ProjectEuler Problem 719 (some hints, but no spoilers)

The Power Sum, a recursive problem by HackerRank