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.

#AuthorScoreLanguageSolution
1Josu San MartinJosu San Martin Expert2,968
RUST
rust-1.95.0
Aug 10, 2026 08:58
648,764,739 ns · 599,366,000 ns · 38,779,000 ns · 2,113,536 B
2Victor MerckléVictor Mercklé Grandmaster2,975
RUST
rust-1.95.0
Aug 9, 2026 22:20
648,495,235 ns · 593,423,000 ns · 46,333,000 ns · 2,117,632 B
3Andrew TsibinAndrew Tsibin Expert4,894
RUST
rust-1.95.0
Aug 9, 2026 11:09
1,062,107,655 ns · 1,022,427,000 ns · 29,792,000 ns · 2,113,536 B
4Bernard TeoBernard Teo Skilled7,476
CPP
g++10.5.0
Aug 11, 2026 16:31
1,617,557,935 ns · 1,568,200,000 ns · 39,337,000 ns · 2,113,536 B
5Yurkov AlekseyYurkov Aleksey Skilled8,532
CPP
g++10.5.0
Aug 10, 2026 18:07
1,845,398,930 ns · 1,801,744,000 ns · 32,829,000 ns · 2,113,536 B
6Yuriy LyfenkoYuriy Lyfenko Expert11,887
CPP
g++10.5.0
Aug 11, 2026 18:08
2,565,791,516 ns · 2,531,745,000 ns · 24,049,000 ns · 2,113,536 B
7DanielDaniel Skilled44,896
RUST
rust-1.95.0
Aug 11, 2026 07:11
9,662,787,425 ns · 9,446,595,000 ns · 206,180,000 ns · 2,117,632 B
8Yehor BondarYehor Bondar Skilled83,184
CPP
clang++20.1.2
Aug 12, 2026 15:26
17,895,470,143 ns · 17,653,308,000 ns · 231,425,000 ns · 2,117,632 B