data-structures · intermediate · ~15 min
Search an open-addressing table the way insertion laid it out.
Look up a key in an open-addressing hash table using linear probing.
Using the same convention as insertion (the value 0 marks an empty slot), implement int table_find(const int *table, int cap, int start, int key) that probes forward from start, wrapping around, and returns the index where key is stored. Return -1 if an empty slot is reached first or all cap slots have been checked.
table: array of cap ints; a 0 entry means empty.cap: the table size.start: the index to begin probing from.key: the value to search for (assumed non-zero).int: index where key is found, or -1 if not present.
table={0,7,8,0}, start=1, key=8 -> 2
table={0,7,8,0}, start=1, key=7 -> 1
table={0,7,8,0}, start=1, key=9 -> -1 (empty slot hit before finding it)
0) slot stops the search and returns -1: the key cannot be stored past a gap.cap slots without a match, return -1.table: cap ints (0 = empty); cap; start in [0, cap); key (non-zero).
int: index where key is stored, or -1 if absent.
Stop at the first empty slot; wrap with modulo and bound the scan by cap.
int table_find(const int *table, int cap, int start, int key) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.