Taro Logo

Design Exam Scores Tracker

Medium
Asked by:
Profile picture
4 views
Topics:
ArraysBinary Search

Alice frequently takes exams and wants to track her scores and calculate the total scores over specific time periods.

Implement the ExamTracker class:

  • ExamTracker(): Initializes the ExamTracker object.
  • void record(int time, int score): Alice takes a new exam at time time and achieves the score score.
  • long long totalScore(int startTime, int endTime): Returns an integer that represents the total score of all exams taken by Alice between startTime and endTime (inclusive). If there are no recorded exams taken by Alice within the specified time interval, return 0.

It is guaranteed that the function calls are made in chronological order. That is,

  • Calls to record() will be made with strictly increasing time.
  • Alice will never ask for total scores that require information from the future. That is, if the latest record() is called with time = t, then totalScore() will always be called with startTime <= endTime <= t.

Example 1:

Input:
["ExamTracker", "record", "totalScore", "record", "totalScore", "totalScore", "totalScore", "totalScore"]
[[], [1, 98], [1, 1], [5, 99], [1, 3], [1, 5], [3, 4], [2, 5]]

Output:
[null, null, 98, null, 98, 197, 0, 99]

Explanation

ExamTracker examTracker = new ExamTracker();
examTracker.record(1, 98); // Alice takes a new exam at time 1, scoring 98.
examTracker.totalScore(1, 1); // Between time 1 and time 1, Alice took 1 exam at time 1, scoring 98. The total score is 98.
examTracker.record(5, 99); // Alice takes a new exam at time 5, scoring 99.
examTracker.totalScore(1, 3); // Between time 1 and time 3, Alice took 1 exam at time 1, scoring 98. The total score is 98.
examTracker.totalScore(1, 5); // Between time 1 and time 5, Alice took 2 exams at time 1 and 5, scoring 98 and 99. The total score is 98 + 99 = 197.
examTracker.totalScore(3, 4); // Alice did not take any exam between time 3 and time 4. Therefore, the answer is 0.
examTracker.totalScore(2, 5); // Between time 2 and time 5, Alice took 1 exam at time 5, scoring 99. The total score is 99.

Constraints:

  • 1 <= time <= 109
  • 1 <= score <= 109
  • 1 <= startTime <= endTime <= t, where t is the value of time from the most recent call of record().
  • Calls of record() will be made with strictly increasing time.
  • After ExamTracker(), the first function call will always be record().
  • At most 105 calls will be made in total to record() and totalScore().

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the valid range of exam scores being added, and can scores contain decimals or are they strictly integers?
  2. How should the system handle the median calculation if no exam scores have been recorded yet?
  3. Are duplicate exam scores allowed, and if so, should each identical score be treated as a distinct data point in the median calculation?
  4. Is there an expected upper bound on the total number of scores that will be added to the data stream?
  5. Should the returned median score be rounded to a specific decimal place, or is standard floating-point precision acceptable?

Brute Force Solution

Approach

Imagine you need to keep track of students and their exam scores while being able to quickly find averages or specific results. The brute force approach simply records every single score on a giant list and completely scans through that entire list from the beginning every time someone asks a question.

Here's how the algorithm would work step-by-step:

  1. Whenever a new score comes in, just write it down at the very end of your growing collection of scores without worrying about order.
  2. When someone asks for the highest or lowest score, look at every single score on your paper from top to bottom, one by one, to find the answer.
  3. When someone asks for an average, look at every single score, add them all together in your head, and then divide by the total count of scores you just counted.
  4. Repeat this thorough, start-to-finish search process for every single request that comes your way, no matter how many times you have to look at the exact same scores over and over again.

Code Implementation

class ExamScoresTracker:
    def __init__(self):
        self.score_collection = []

    def record_score(self, current_score):
        # We append each score to the end without sorting to keep writes as fast as possible
        self.score_collection.append(current_score)

    def get_maximum_score(self):
        # A full linear scan is required because unsorted data provides no structural shortcuts
        highest_score = self.score_collection[0]
        for exam_score in self.score_collection:
            if exam_score > highest_score:
                highest_score = exam_score
        return highest_score

    def get_average_score(self):
        # Summing all elements dynamically on every query guarantees accuracy despite raw storage
        total_score_sum = 0
        score_count = 0
        for exam_score in self.score_collection:
            total_score_sum += exam_score
            score_count += 1
        return total_score_sum / score_count

Big(O) Analysis

Time Complexity
O(n) – When a query for the average, highest, or lowest score is made, the brute force approach requires a complete scan of the entire collection of scores from start to finish. The input size n, which represents the total number of scores recorded so far, directly drives the cost since every single score must be visited one by one. Across the entire dataset, this requires examining n elements per query. This linear progression results in approximately n operations per request, which simplifies to O(n).
Space Complexity
O(N) – The brute force approach requires a growing collection of scores to store every single score as it comes in. As the total number of scores N increases, this list grows linearly to hold each new entry without reordering. The auxiliary space is directly driven by this single list storing all N recorded exam scores. Therefore, the total extra memory scales in direct proportion to the input size N, resulting in a linear space complexity.

Optimal Solution

Approach

To efficiently track and retrieve the highest exam scores, the optimal strategy is to keep the scores organized in order as they arrive. This ensures that whenever someone asks for the top results, they can be found instantly without having to search through everything.

Here's how the algorithm would work step-by-step:

  1. When a new exam score is reported, immediately place it into a holding area so that all scores remain neatly sorted from highest to lowest.
  2. If multiple students achieve the exact same score, keep all of them grouped together so no one is left out.
  3. Whenever a request is made for the top a certain number of scores, simply look at the front of the organized group and collect the requested amount.
  4. Because the scores are always kept in order, you never have to waste time searching or sorting from scratch when a request comes in.
  5. Continue this process smoothly as new scores arrive and requests are made, ensuring fast and accurate results every time.

Code Implementation

import bisect

class ExamScoresTracker:
    def __init__(self):
        self.all_recorded_scores = []

    def record_score(self, new_exam_score):
        # We insert the score using a negative representation to maintain descending order easily.
        bisect.insort(self.all_recorded_scores, -new_exam_score)

    def get_top_scores(self, requested_count):
        # Collecting the top results requires taking elements from the front of the sorted list.
        top_scores_collection = []
        for index in range(min(requested_count, len(self.all_recorded_scores))):
            top_scores_collection.append(-self.all_recorded_scores[index])

        # Returning scores in their original positive format ensures clarity for the client.
        return top_scores_collection

Big(O) Analysis

Time Complexity
O(n log n) – For each of the n incoming exam scores, we insert it into a sorted data structure which takes logarithmic time relative to the current number of elements. When a request is made for the top scores, retrieving them operates in constant time because the data is already pre-sorted. This insertion cost accumulates across all n elements to approximate n * log(n) operations. Therefore, the total time complexity simplifies to O(n log n).
Space Complexity
O(n) – To keep all exam scores neatly sorted as they arrive, we store them in an auxiliary ordered data structure such as a balanced binary search tree or a priority queue. Because every single reported score must be retained within this structure to handle future top-score queries, the extra memory grows directly proportional to the total number of scores. Therefore, where N represents the total number of exam scores processed, the auxiliary space complexity is linear with respect to N.

Edge Cases

Retrieving the median when no scores have been recorded yet
How to Handle:
The system should handle this gracefully by throwing an appropriate exception or returning a default sentinel value like zero.
Data stream containing only one recorded score
How to Handle:
The two-heap architecture naturally places the single element in the max-heap, and the median retrieval simply returns this value cast as a float.
Processing an extremely large volume of incoming scores in a continuous stream
How to Handle:
Using the dual-heap approach ensures that both insertion and median retrieval operate in logarithmic and constant time respectively, maintaining high scalability.
Streams consisting entirely of identical score values
How to Handle:
Duplicate handling in the heaps correctly balances elements of equal value across the structures to compute the accurate midpoint.
Scores containing negative integers, zeros, or extreme boundary values
How to Handle:
Standard numerical comparison logic in the heaps remains unaffected by the sign or magnitude as long as the data types prevent overflow.
Even versus odd total counts of recorded scores
How to Handle:
The algorithm checks the combined size of the heaps to either return the top of the max-heap or average the roots of both heaps.
Integer overflow when calculating the average of two large scores for an even-sized stream
How to Handle:
Casting at least one of the values to a floating-point type prior to addition prevents arithmetic overflow and preserves fractional precision.
Memory constraints when scaling to millions of entries in a persistent stream
How to Handle:
The linear space complexity storing all inputs in memory is optimal for this design unless a sliding window constraint is introduced.