AlgoFrames

Count collisions

Standard · Write code · about 10 min

A hash table has size buckets and hashes a key with key mod size. Insert the distinct keys in keys in order. A collision happens when a key lands in a bucket that already holds at least one key.

Return the number of collisions.

Example 1

Input:

[[12,7,3,22,9],5]

Output:

2

7 and 22 land in bucket 2 after 12.

Example 2

Input:

[[1,2,3],5]

Output:

0

Every key gets its own bucket.

Constraints

  • 0 ≤ keys.length ≤ 10,000
  • keys are distinct, 0 ≤ key ≤ 1,000,000
  • 1 ≤ size ≤ 1,000

Learn the idea first: Hash tables with separate chaining, a visual lesson.

More Hash tables with separate chaining problems