AlgoFrames

Bucket histogram

Standard · Write code · about 8 min

A table has m buckets and sends a key to bucket key mod m. Count how many keys from keys land in each bucket. Count a repeated key every time it appears.

Return an array of length m whose entry i is the number of keys in bucket i.

Example 1

Input:

[[12,7,3,21,9,15],5]

Output:

[1,1,2,1,1]

12 and 7 share bucket 2.

Example 2

Input:

[[10,20,30],10]

Output:

[3,0,0,0,0,0,0,0,0,0]

Multiples of 10 all land in bucket 0.

Constraints

  • 0 ≤ keys.length ≤ 10,000
  • 0 ≤ key ≤ 1,000,000
  • 1 ≤ m ≤ 1,000

Learn the idea first: Hash functions: from key to bucket index, a visual lesson.

More Hash functions: from key to bucket index problems