AlgoFrames

Implement resize

Challenge · Write code · about 20 min

Build a chaining hash table that grows. It starts with size buckets, each a list, and a key goes to bucket key mod m, where m is the current number of buckets. Insert the distinct keys of keys in order; each new key joins the end of its chain.

After each insert, if keys ÷ buckets is above 0.75, resize: make 2m empty buckets, then walk the old buckets from 0 to m − 1, each chain front to back, and append every key to bucket key mod 2m.

Return every key of the final table, read bucket by bucket from bucket 0, each chain front to back. Do not use a built-in map or set.

Example 1

Input:

[4,[4,8,12,16]]

Output:

[8,16,4,12]

The 4th insert resizes to 8: 4 and 12 go to bucket 4, 8 and 16 to bucket 0.

Example 2

Input:

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

Output:

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

After the resize the buckets are 1: 9, 2: 2, 3: 11, 5: 5, 6: 14, 7: 7.

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