AlgoFrames

Bucket index of every key

Standard · Write code · about 8 min

A table has m buckets and uses the key itself as its hash value. Return the bucket index of each key in keys, in order.

A bucket index must lie between 0 and m − 1, also for negative keys. For example, −3 goes to bucket 1 when m = 4, because −3 = −1 · 4 + 1.

Example 1

Input:

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

Output:

[2,2,3,1]

12 and 7 both leave remainder 2.

Example 2

Input:

[[-3,8,-10],4]

Output:

[1,0,2]

Negative keys still map into 0 … 3.

Constraints

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

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

More Hash functions: from key to bucket index problems