Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Coding problem

    The two best scores in each class

    MediumAbout 25 minFull AccessLearn it: OrderBy Under the Hood: O(n log n), an O(n) Buffer, Stability and Top-k

    The task

    The school's prize list names the two best students of every class.

    Complete TopTwoPerClass(List<Score> scores). Score is a record with a Class, a Student and the Points scored. For each class, return its two highest scores, highest first; students with the same points are sorted by name in ascending ordinal order, which compares characters by their numeric values. A class with one student gives just that score. List the classes in ascending ordinal order, each class's rows together. An empty list gives an empty list. The list and its scores are never null, class and student names hold only lowercase English letters and digits, and a student appears once per class.

    Signature

    public record Score(string Class, string Student, int Points);
    public static List<Score> TopTwoPerClass(List<Score> scores)

    Examples

    • [("9a", "amy", 70), ("9b", "ben", 88), ("9a", "cara", 91), ("9a", "dev", 85), ("9b", "eli", 60)] → [("9a", "cara", 91), ("9a", "dev", 85), ("9b", "ben", 88), ("9b", "eli", 60)]. In 9a, amy's 70 is third, so she is left out; 9b has only two students.
    • [("9c", "zoe", 50), ("9c", "abe", 50), ("9c", "max", 50)] → [("9c", "abe", 50), ("9c", "max", 50)]. All three tie, so the two names that come first win.

    Limits: Up to 400,000 scores in up to 40,000 classes.

    The tests check: an empty list, a class with one student, ties settled by name, the best first within a class, classes A to Z, two per class rather than two overall, and 400,000 scores in time.

    Hints

      Your code

      C#Solution.csLoading the editor…

      Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;

      public record Score(string Class, string Student, int Points);
      
      public static class Solution
      {
          // The two best scores of every class (ties by name), classes A to Z.
          public static List<Score> TopTwoPerClass(List<Score> scores)
          {
              throw new NotImplementedException();
          }
      }

      This problem comes with TechInterviewNotes Full Access

      Unlock all paid content on TechInterviewNotes.