THINK FIRST·CODE LATER

← All labs

Separate Chaining with Rehashing

Problem

Read the initial number of buckets m, the number of keys n, and then n integer keys. Insert them in order into a separate-chaining hash table with h(k) = Math.floorMod(k, m), appending each new key to the end of its bucket's list.

  • A key that is already present prints Duplicate: K and is skipped.
  • After a key has been added, if size > m (load factor above 1), resize to 2m + 1 buckets and print Resized to M. Rehash by visiting the old buckets from 0 to m − 1, each from front to back, appending every key to the end of its new bucket.

Finally print each bucket as i: a -> b -> c, or i: (empty), and a summary line.

Input:

2 5 4 1 6 3 9

Output:

Resized to 5
0: (empty)
1: 6 -> 1
2: (empty)
3: 3
4: 4 -> 9
Size: 5, Buckets: 5, Longest chain: 2

(After 4, 1, 6 the table has 3 keys in 2 buckets, so it grows to 5. Bucket 0 held 4 → 6 and is rehashed first, which is why 6 comes before 1 in the new bucket 1.)

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.