AlgoFrames

Total rehash moves

Standard · Write code · about 10 min

A hash table starts with size buckets. You insert the distinct keys of keys one by one. After each insert, if keys ÷ buckets is above 0.75, the table doubles and rehashes every key it holds. Each rehashed key counts as one move.

Return the total number of moves over all inserts. Compare it with the number of keys: it stays below 2n.

Example 1

Input:

[4,[5,9,2,14,7,11]]

Output:

4

The only resize happens at the 4th key and moves all 4 keys.

Example 2

Input:

[2,[3,8,5,12,6,1,10]]

Output:

13

Resizes at the 2nd, 4th and 7th key move 2 + 4 + 7 = 13 keys.

Constraints

  • 1 ≤ size ≤ 1,000
  • 0 ≤ keys.length ≤ 10,000
  • Keys are distinct whole numbers ≥ 0

Learn the idea first: Load factor and resizing, a visual lesson.

More Load factor and resizing problems