Skip to content
BytePatterns

Where Linear Probing Lands

MediumHash Tables#open-addressing#union-find~30m

Problem

A hash table has m slots numbered 0 to m - 1 and uses linear probing. Keys, all zero or more, are inserted in order: key k aims at slot k mod m, and if that slot is taken it tries the next one, wrapping from m - 1 back to 0, until it finds a free slot. There are never more keys than slots. Return the slot each key ends up in, and avoid re-walking long runs of taken slots, because a bad hash can pile every key onto one spot.

Examples

Input:  m = 7, keys = [10, 3, 17, 24, 5]
Output: [3, 4, 5, 6, 0]
Why:    10, 3, 17 and 24 all aim at slot 3 and spread out to 3-6;
        5 finds 5 and 6 taken and wraps around to 0
Input:  m = 5, keys = [4, 9, 14]
Output: [4, 0, 1]
Why:    every key aims at slot 4, so the later ones wrap around
Input:  m = 1, keys = [42]
Output: [0]
Why:    edge case, a one-slot table has only one place to go

Hints

0 / 3

Stuck on the idea rather than the code? When Hashing Fails covers it.