Group by sum Sergey Svistunov

Aggregate 125,000,000 key/value records by key as fast as possible.

The task is equivalent to this query:

SELECT SUM(s * s) FROM (
    SELECT SUM(value) AS s FROM records GROUP BY key
)

Input

Exactly 125,000,000 records on STDIN, 8 bytes each, back to back (1,000,000,000 bytes in total):

Offset Type Field
0 uint32 little-endian key
4 uint32 little-endian value

Guarantees:

  • The records contain exactly 4,000,000 distinct keys.
  • A key is an arbitrary value in [0, 2^32) and may repeat any number of times.
  • A value is an arbitrary value in [0, 2^32).

Output

Group the records by key, sum the values of each group, then write the sum of the squares of those group sums to STDOUT as a decimal string:

answer = SUM(sum_k * sum_k) over all 4,000,000 distinct keys k

Both the squaring and the outer sum are computed modulo 2^64 (unsigned 64-bit wraparound). An individual group sum never overflows uint64.

Example

For the six records

key=7 value=10
key=3 value=4000000000
key=7 value=20
key=9 value=1
key=3 value=4000000000
key=7 value=30

the group sums are sum_7 = 60, sum_3 = 8000000000 and sum_9 = 1, so

60*60 + 8000000000*8000000000 + 1*1 = 64000000000000003601
64000000000000003601 mod 2^64       = 8659767778871348753

and the program prints 8659767778871348753.

Back to listOct 4, 2026 15:17Karthik ReddyKarthik ReddyError
Source Code

Source code access is restricted. Log in to request access.

Challenge History

No challenges yet.

Run Statistics
#DateScoreWall TimeCPU UserCPU SystemMemoryError
1Oct 4, 2026 15:1802,119,338,3162,058,916,00049,460,0002,117,632expected "992533738045465113 ", got "distinct 4000000 top 7671053 | 1K 0.459 2K 0.502 4K 0.544 16K 0.629 64K 0.715 256K 0.802 1000K 0.895 | samp16K 0.627 | samp64K 0.707 "
2Oct 4, 2026 15:1802,121,971,4282,062,160,00049,285,0002,117,632expected "4418889979238288054 ", got "distinct 4000000 top 7670694 | 1K 0.459 2K 0.502 4K 0.544 16K 0.629 64K 0.715 256K 0.802 1000K 0.895 | samp16K 0.627 | samp64K 0.707 "
3Oct 4, 2026 15:1802,131,238,0302,069,947,00050,635,0002,113,536expected "11058330560058044605 ", got "distinct 4000000 top 7672421 | 1K 0.459 2K 0.502 4K 0.544 16K 0.629 64K 0.715 256K 0.802 1000K 0.895 | samp16K 0.627 | samp64K 0.707 "