Implement quadratic probing with resize
Challenge · Write code · about 25 min
A table starts with size empty slots, where size is a power of two. Insert the distinct keys of keys in order.
- Probe j of key K tries slot (K + j(j+1)/2) mod m for j = 0, 1, 2, …, where m is the current size. The first empty slot takes K.
- Before each insert, if the table would then hold more than m ÷ 2 keys, double m. Re-insert every stored key into the new empty table, in the order the keys were first inserted.
Return the final slot of each key, in the order of keys.
Example 1
Input:
[[5,13,21,1],4]
Output:
[5,6,0,1]
21 would make 3 keys in 4 slots, so the table grows to 8. Then 21 probes 5, 6 and lands in 0.
Example 2
Input:
[[1,2,3],8]
Output:
[1,2,3]
No collisions and no resize.
Constraints
- 0 ≤ keys.length ≤ 10,000
- keys are distinct, 0 ≤ key ≤ 1,000,000
- 1 ≤ size ≤ 1,024, size is a power of two
Learn the idea first: Open addressing: linear, quadratic probing, double hashing, a visual lesson.
More Open addressing: linear, quadratic probing, double hashing problems
- Follow the probes Warm-up
- Clustering Standard
- Predict a double-hashing slot Standard
- Fill a table with linear probing Standard
- Implement insert with tombstones Standard