Prefix Totals by Value Across Duplicate-Heavy Records
SQL & DataAuto-graded · 17 test casesLast 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 integerid(unique) and integerval. valmay 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The total for a record depends only on its value, so we do the work once per distinct value instead of once per record.
- Group by value. For each distinct value
v, compute the sum of all records that have that value. This isvtimes its number of occurrences. Duplicates collapse into one bucket. - Running total. Sort the distinct values ascending and accumulate the bucket sums. After processing value
x, the running total equals the sum of every record with value<= x. - Map back. For each input record, look up its value in the accumulated totals and emit
[id, val, total], keeping the original order.
Why it is correct
Let B(v) be the sum of all records with value exactly v. The desired total for a record with value x is the sum of B(v) over all distinct v <= x. Processing distinct values in ascending order, the running total after adding B(x) is exactly that sum: every smaller or equal value has been added and no larger one has. Records with equal values share a bucket, which is added in full before the total is recorded, so ties are counted fully. Negative values need no special treatment, since the definition is just a sum over values <= x.
Complexity
With n records and d distinct values (d <= n):
- Time:
O(n + d log d)for grouping, sorting the distinct values, and mapping back. - Space:
O(d)extra, plusO(n)for the output.
The SQL analogue is the same idea: GROUP BY val, then a window SUM(...) OVER (ORDER BY val) over the distinct values, then join back to the table. A single-pass window over the raw table also works, but only with a RANGE frame (so tied rows are peers); a ROWS frame would miss tied rows.
Reference solution
from typing import List
from collections import defaultdict
def prefix_totals_by_value(records: List[List[int]]) -> List[List[int]]:
# Sum contributions per distinct value
bucket = defaultdict(int)
for _, val in records:
bucket[val] += val
# Running total across distinct values in ascending order
cumulative = {}
running = 0
for val in sorted(bucket):
running += bucket[val]
cumulative[val] = running
# Map each record back to its total, preserving input order
return [[rid, val, cumulative[val]] for rid, val in records]