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,
record() will be made with strictly increasing time.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();98 + 99 = 197.Constraints:
1 <= time <= 1091 <= score <= 1091 <= startTime <= endTime <= t, where t is the value of time from the most recent call of record().record() will be made with strictly increasing time.ExamTracker(), the first function call will always be record().105 calls will be made in total to record() and totalScore().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:
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:
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_countTo 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:
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| Case | How to Handle |
|---|---|
| Retrieving the median when no scores have been recorded yet | 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 | 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 | 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 | 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 | 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 | 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 | 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 | The linear space complexity storing all inputs in memory is optimal for this design unless a sliding window constraint is introduced. |