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
1Victor MerckléVictor Mercklé Grandmaster2,380
CPP
clang++20.1.2
Aug 18, 2026 14:01
520,075,516 ns · 490,426,000 ns · 21,321,000 ns · 2,121,728 B
2Tomislav TunkovicTomislav Tunkovic Expert2,789
GO
go1.26.2
Aug 17, 2026 13:08
608,263,740 ns · 572,952,000 ns · 26,793,000 ns · 2,129,920 B
3marko1597marko1597 Expert2,859
CPP
g++14.2.0
Aug 14, 2026 11:27
624,652,252 ns · 601,084,000 ns · 13,749,000 ns · 2,117,632 B
4Josu 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
5Andrew TsibinAndrew Tsibin Expert3,386
RUST
rust-1.95.0
Aug 13, 2026 10:07
738,148,663 ns · 687,208,000 ns · 40,992,000 ns · 2,113,536 B
6Andrew EpsteinAndrew Epstein Skilled4,207
CPP
g++14.2.0
Aug 23, 2026 15:29
914,581,400 ns · 899,259,000 ns · 5,427,000 ns · 2,113,536 B
7Yuriy LyfenkoYuriy Lyfenko Expert4,852
CPP
clang++19.1.1
Aug 14, 2026 22:31
1,053,399,549 ns · 988,838,000 ns · 54,374,000 ns · 2,113,536 B
8Bernard 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
9Yehor BondarYehor Bondar Skilled8,268
CPP
clang++20.1.2
Aug 13, 2026 09:09
1,788,642,463 ns · 1,743,879,000 ns · 33,905,000 ns · 2,121,728 B
10Yurkov 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
11DanielDaniel 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