LeetCode #3709 — MEDIUM

Design Exam Scores Tracker

Move from brute-force thinking to an efficient approach using array strategy.

Solve on LeetCode
The Problem

Problem Statement

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().
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: 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

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Binary Search · Design

Example 1

["ExamTracker","record","totalScore","record","totalScore","totalScore","totalScore","totalScore"]
[[],[1,98],[1,1],[5,99],[1,3],[1,5],[3,4],[2,5]]
Step 02

Core Insight

What unlocks the optimal approach

  • Maintain two arrays: <code>times</code> (append each <code>time</code>) and <code>prefix</code> where <code>prefix[i]</code> is sum of scores up to index <code>i</code>.
  • Use binary search to find indices: <code>l = lower_bound(times, startTime)</code> and <code>r = upper_bound(times, endTime) - 1</code>.
  • If <code>l > r</code> there are no exams, so return <code>0</code>; otherwise compute total using the <code>prefix</code>.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3709: Design Exam Scores Tracker
class ExamTracker {
    private List<Integer> times = new ArrayList<>();
    private List<Long> pre = new ArrayList<>();

    public ExamTracker() {
        times.add(0);
        pre.add(0L);
    }

    public void record(int time, int score) {
        times.add(time);
        pre.add(pre.getLast() + score);
    }

    public long totalScore(int startTime, int endTime) {
        int l = binarySearch(startTime) - 1;
        int r = binarySearch(endTime + 1) - 1;
        return pre.get(r) - pre.get(l);
    }

    private int binarySearch(int x) {
        int l = 0, r = times.size();
        while (l < r) {
            int mid = (l + r) >> 1;
            if (times.get(mid) >= x) {
                r = mid;
            } else {
                l = mid + 1;
            }
        }
        return l;
    }
}

/**
 * Your ExamTracker object will be instantiated and called as such:
 * ExamTracker obj = new ExamTracker();
 * obj.record(time,score);
 * long param_2 = obj.totalScore(startTime,endTime);
 */
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(log n)
Space
O(1)

Approach Breakdown

LINEAR SCAN
O(n) time
O(1) space

Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.

BINARY SEARCH
O(log n) time
O(1) space

Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).

Shortcut: Halving the input each step → O(log n). Works on any monotonic condition, not just sorted arrays.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Boundary update without `+1` / `-1`

Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.

Usually fails on: Two-element ranges never converge.

Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.