KatInterview

Prefix Totals by Value Across Duplicate-Heavy Records

SQL & DataAuto-graded · 17 test cases
MediumAuto-gradedSQL & Dataaggregationprefix-sumsorting

Last updated

Compute, for each record, the total of all values in the dataset that do not exceed its own value, handling ties and large inputs efficiently via grouping and a running total.

You are given a list of records, where each record is a pair [id, val]: a unique identifier and an integer value.

For every record, compute the sum of the val of all records in the whole list whose val is less than or equal to this record's val. The comparison is by value only, not by position or id. The record itself is included in its own total, and records with an equal value always count fully (every record sharing the same value is included, regardless of order).

Return a list of triples [id, val, total], one per input record, in the same order as the input.

This task mirrors a SQL problem on a table numbers(id, val). A correlated subquery per row would take quadratic time, so aim for something that scales better: group by value first, accumulate over the distinct values in ascending order, then map each record back to its total.

Constraints

  • 0 <= len(rows) <= 10^5
  • Each record is [id, val] with integer id (unique) and integer val.
  • val may repeat, and may be zero or negative. Do not assume totals grow with the value.
  • An empty input returns an empty list.
  • The output must preserve the input order and contain exactly one triple per input record.
  • Python integers do not overflow, so no special handling is needed for large sums.

Examples

Example 1

Input: prefix_totals_by_value([[1, 1], [2, 2], [3, 15], [4, 14], [5, 13], [6, 2], [7, 1]])

Output: [[1, 1, 2], [2, 2, 6], [3, 15, 48], [4, 14, 33], [5, 13, 19], [6, 2, 6], [7, 1, 2]]

Hints

Hint 1

The answer for a record depends only on its value, not on its id or position, so you can compute it once per distinct value.

Hint 2

Group the records by value and add up each group's contribution (value times how many times it appears). Then sort the distinct values.

Hint 3

Walk the sorted distinct values keeping a running total, store the total for each value in a dictionary, and finally look up each original record's value to build the output in input order.