data-structures · intermediate · ~15 min

Find a free slot (linear probing)

Implement linear probing with wrap-around.

Challenge

Find the first empty slot in an open-addressing hash table using linear probing.

Task

An open-addressing table stores ints and uses the value 0 to mean an empty slot. Implement int find_slot(const int *table, int cap, int start) that scans forward from index start, wrapping around the end, and returns the index of the first empty slot. If the table is full, return -1.

Input

  • table: array of cap ints; a 0 entry means empty.
  • cap: the table size (cap > 0).
  • start: the index to begin probing from, 0 <= start < cap.

Output

int: index of the first empty (0) slot found by probing forward from start, or -1 if none exists.

Example

table={1,2,0,3}, start=2   ->   2
table={1,2,0,3}, start=0   ->   2    (probes to index 2)
table={1,2,0,3}, start=3   ->   2    (wraps to index 2)
table={1,1,1},   start=0   ->   -1   (full)

Edge cases

  • A full table (no 0 entries) returns -1.
  • Probing wraps from the last index back to index 0.

Input format

table: cap ints (0 = empty); cap > 0; start in [0, cap).

Output format

int: index of the first empty slot probing forward from start, or -1 if full.

Constraints

Probe at most cap slots, wrapping with modulo.

Starter code

int find_slot(const int *table, int cap, int start) {
    /* TODO */
    return -1;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.