#3709

Design Exam Scores Tracker

Medium
ArrayBinary SearchDesignPrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

By maintaining a prefix sum array, we can quickly calculate the total score for any time range using binary search to find the relevant indices.

⚙️

Algorithm

3 steps
  1. 1Step 1: Store times and scores in separate lists.
  2. 2Step 2: Maintain a prefix sum array where each index holds the cumulative score up to that index.
  3. 3Step 3: Use binary search to find the indices corresponding to startTime and endTime, then return the difference of prefix sums.
solution.py15 lines
1class ExamTracker:
2    def __init__(self):
3        self.times = []
4        self.scores = []
5        self.prefix = []
6
7    def record(self, time, score):
8        self.times.append(time)
9        self.scores.append(score)
10        self.prefix.append((self.prefix[-1] if self.prefix else 0) + score)
11
12    def totalScore(self, startTime, endTime):
13        l = bisect.bisect_left(self.times, startTime)
14        r = bisect.bisect_right(self.times, endTime) - 1
15        return self.prefix[r] - (self.prefix[l-1] if l > 0 else 0)

Complexity note: The prefix sum allows us to compute the total in constant time after linear time setup.

  • 1Using prefix sums allows for efficient range queries.
  • 2Binary search optimizes the search for time indices.

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