Peak Average Score: Overflow, Large Files, and Java Concurrency
Arrays & HashingModel answerLast updated
Aggregate student scores to find the highest per-student average, then extend the solution for huge files, negative values, integer overflow, and multithreaded processing.
You receive a list of exam records. Each record contains a student's name and one integer score they received, represented as a decimal string. Write a method that returns the highest average score any student has earned, truncated down to a whole number.
public static int highestAverage(String[][] records)
Each element is a two-entry array {name, score}:
{{"Bob", "87"}, {"Mike", "35"}, {"Bob", "52"}, {"Jason", "35"}, {"Mike", "55"}, {"Jessica", "99"}}
Bob's scores sum to 139 over 2 entries (average 69.5), Mike's sum to 90 over 2 (average 45), Jason has one score of 35, and Jessica has one score of 99. Return 99.
Write the implementation on paper — no IDE or compiler. Each part below asks you to evolve your previous code rather than describe a solution in the abstract.
Before writing anything, ask yourself:
- What should be returned when the input is empty?
- Should a malformed row (wrong column count, non-numeric score) be skipped or cause an immediate failure?
- Are names case-sensitive? Should surrounding whitespace be stripped?
- What range can a score take? Is there a limit on how many scores one student can accumulate?
Part 1: All Records Fit in Memory
Implement highestAverage for an input small enough to load completely into memory.
Your solution should:
- Make a single pass and store only summary data per student, not every individual score
- Use the correct rounding behavior when computing integer averages
- Be analyzed for time and space complexity in terms of total records and distinct students
Part 2: The File Is Too Large for RAM
The same records now arrive from a log file that is many times larger than available heap space. Adapt your solution.
Address both sub-cases:
- The number of distinct students is small enough that a summary map fits in memory, but the raw record count is enormous
- The number of distinct students is itself too large to fit in memory at once
Cover the I/O cost of your approach and explain why partial aggregates can be combined correctly.
Part 3: Negative Scores and Integer Overflow
The problem changes in two ways: scores may be negative, and a single student's cumulative score total may exceed the range of a Java int.
Identify and fix:
- Where rounding behavior in your original code silently gives the wrong answer for negative averages
- Any initial values that implicitly assumed non-negative scores
- The safest type choice for accumulated sums, and how to handle inputs that would overflow even that type
Explain whether floating-point arithmetic is a suitable replacement and why.
Part 4: Multithreading, Atomics, and Locks
Rewrite the in-memory solution to distribute work across multiple threads.
Then answer the following without looking anything up:
- What does "atomic" mean for an operation? What guarantee do Java's classes in
java.util.concurrent.atomic(for example,AtomicLong) provide that a plainlongfield does not? - What are the behavioral differences between
synchronizedandReentrantLock? When would you reach for one over the other? - How does your design ensure that the thread collecting final results sees every write made by the worker threads?
Hints
Hint 1
For the out-of-memory case, separate the two distinct problems: too many raw records versus too many distinct students. Each has its own solution, and only the second one requires repartitioning the data on disk.
Hint 2
Java integer division truncates toward zero, not toward negative infinity. For a negative quotient such as -7 / 2, those two behaviors give different results. Check whether your code actually needs Math.floorDiv.
Hint 3
Keep worker threads entirely free of shared mutable state during the processing phase. Each thread builds its own local map, and the main thread merges after all workers have finished. This sidesteps locking during the hot path entirely.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying Questions First
Pin down the contract before touching code. A reasonable baseline: return 0 (or throw IllegalArgumentException) for empty input; throw on malformed rows unless told otherwise; treat names as case-sensitive and pre-trimmed; assume scores fit in int for Part 1, then relax that in Part 3.
Part 1: In-Memory Solution
One pass is enough. Store a two-element long[] per student — index 0 for the running sum, index 1 for the count — and update as you iterate.
public static int highestAverage(String[][] records) {
if (records == null || records.length == 0) {
throw new IllegalArgumentException("No records provided");
}
Map<String, long[]> agg = new HashMap<>();
for (String[] record : records) {
String name = record[0].trim();
long score = Long.parseLong(record[1].trim());
long[] bucket = agg.computeIfAbsent(name, k -> new long[2]);
bucket[0] += score; // sum
bucket[1]++; // count
}
long best = Long.MIN_VALUE;
for (long[] bucket : agg.values()) {
long avg = Math.floorDiv(bucket[0], bucket[1]);
if (avg > best) best = avg;
}
return (int) best;
}
Complexity: O(n) time, O(s) space where n is the total number of records and s is the number of distinct students. Nothing per-student grows with n; the map stays bounded by s.
Part 2: Data Larger Than Memory
Two separate problems hide under this heading.
Case A — many records, manageable number of students. If the per-student summary map fits in RAM but the raw file does not, stream the file line by line, parse each record, update the map, and discard the raw data. Memory stays at O(s) regardless of how many records exist. Java's BufferedReader with a reasonably sized buffer handles this well.
Case B — too many distinct students. Now even the map overflows. Hash-partition by student name into P temporary files (hash the name, take modulo P). Every record for a given student lands in the same file. Each file holds roughly 1/P of all students. Process each partition independently — build a map, compute averages, note the per-partition maximum — then take the overall maximum across all P results.
Correctness follows because sum and count are both additive: totalSum = sum1 + sum2, totalCount = count1 + count2. The final average is computed only after all records for a student are seen, so partitioning does not introduce error. The I/O cost is one full read-and-write pass to partition, plus one full read pass to aggregate, giving roughly 2× the file size in I/O.
Part 3: Negative Scores and Overflow
Rounding bug. Java integer division truncates toward zero: -7 / 2 is -3, not -4. The correct floor for -3.5 is -4. Replace bare division with Math.floorDiv(sum, count) everywhere, which rounds toward negative infinity and matches the mathematical definition of "truncate down."
Overflow. Summing many large scores into an int wraps silently. Switch sum accumulators to long (already done above). If scores or record counts are pathological enough that even a long could overflow, use Math.addExact to throw ArithmeticException on overflow rather than silently wrapping, or use BigInteger.
Floating point is not a fix. A double has 53 bits of mantissa. For large integer sums this introduces representation error, and the rounding behavior of floating-point division is not the same as floor division. Integer arithmetic with Math.floorDiv is both exact and correct.
Initial values. Using 0 as the starting "max average" silently works when all scores are non-negative. With negative averages, 0 is larger than any real answer. Start the comparison from Long.MIN_VALUE as shown above, or track a nullable best.
Part 4: Multithreading, Atomics, and Locks
Parallel design. Divide the records array into T contiguous slices, one per thread. Each thread builds a completely independent local HashMap — no sharing during the processing phase. When all threads have finished (Thread.join()), the main thread merges the local maps and finds the global maximum.
public static int highestAverageConcurrent(String[][] records, int T)
throws InterruptedException {
int n = records.length;
List<Map<String, long[]>> partials = new CopyOnWriteArrayList<>();
Thread[] workers = new Thread[T];
for (int t = 0; t < T; t++) {
final int lo = t * (n / T);
final int hi = (t == T - 1) ? n : lo + (n / T);
workers[t] = new Thread(() -> {
Map<String, long[]> local = new HashMap<>();
for (int i = lo; i < hi; i++) {
String name = records[i][0].trim();
long score = Long.parseLong(records[i][1].trim());
local.computeIfAbsent(name, k -> new long[2]);
long[] b = local.get(name);
b[0] += score;
b[1]++;
}
partials.add(local);
});
workers[t].start();
}
for (Thread w : workers) w.join();
// Single-threaded merge — no lock needed here
Map<String, long[]> merged = new HashMap<>();
for (Map<String, long[]> partial : partials) {
for (var entry : partial.entrySet()) {
long[] dst = merged.computeIfAbsent(entry.getKey(), k -> new long[2]);
dst[0] += entry.getValue()[0];
dst[1] += entry.getValue()[1];
}
}
long best = Long.MIN_VALUE;
for (long[] b : merged.values()) {
best = Math.max(best, Math.floorDiv(b[0], b[1]));
}
return (int) best;
}
What "atomic" means. An atomic operation either completes entirely or not at all, with no observable intermediate state. On a 64-bit JVM, even reading or writing a long field is not guaranteed atomic by the Java Memory Model — a thread can see a half-written value. AtomicLong wraps a long and provides read-modify-write operations like incrementAndGet and compareAndSet that are guaranteed to be atomic and visible across threads without explicit locking.
synchronized vs. ReentrantLock. Both provide mutual exclusion and memory visibility. synchronized is simpler: it is built into the language, cannot be forgotten to release (the compiler inserts the release on block exit), and is sufficient for most cases. ReentrantLock adds capabilities synchronized lacks: tryLock with a timeout (avoids permanent blocking), lockInterruptibly (lets a waiting thread respond to interruption), and multiple Condition objects per lock for finer-grained wait/notify patterns. The failure mode for synchronized is accidental lock nesting causing deadlock; the failure mode for ReentrantLock is forgetting unlock() in a finally block and holding the lock forever. Prefer synchronized for straightforward critical sections; reach for ReentrantLock when you need timed acquisition or multiple conditions.
Memory visibility. Thread.join() establishes a happens-before edge: all writes made by a thread before it terminates are visible to any thread that returns from join() on it. No additional volatile fields or locks are needed on the local maps because the main thread only reads them after joining every worker.