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 5, 2026 04:47Karthik 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 5, 2026 04:480204,478,102173,288,00020,057,0002,113,536expected "9097243807126253454 ", got "7cb778e5 e56f4280 ac562cb6 d47f2684 b80aa39c c37baec6 51145636 3879a6d4 dedd731a 2e5090c1 167b2831 c256d2b 5c01570a a2a1da1e 91ea3778 cfaddaec 490668 30711 "
2Oct 5, 2026 04:480204,680,451173,474,00020,672,0002,113,536expected "12403968183797856165 ", got "546c9a2f e6b8c3d2 f0210f0a 28b110a6 a83ecff7 3956dedc 64a58ce7 4f3c173a 8fc2ef9d 94c7f59f 57f19640 b9e83021 7e8beaf6 771d070c 1d838adc 784b826c 490272 30728 "
3Oct 5, 2026 04:480207,679,588176,619,00020,574,0002,113,536expected "8299772302317010615 ", got "8e04c330 5b2ccc8b 4e0eab58 893bb429 4aafc3ab e62913f8 4bd4c11d 1f163c26 6522d370 929a94e4 6568ad85 15c4c72e 415fab37 79e18f42 460a2519 6bc621b6 490129 30423 "