data-structures · advanced · ~15 min

Int→int hash table (open addressing)

Open-addressing hash table: probing, slot reuse, find-or-insert.

Challenge

Implement a simple fixed-capacity int→int hash table with linear probing. The supplied struct is:

typedef struct {
    int *keys; int *vals; unsigned char *used;
    size_t cap, len;
} htab_t;

Implement:

  • int ht_init(htab_t *h, size_t cap) — allocate the three arrays, zero used.
  • void ht_free(htab_t *h)
  • int ht_set(htab_t *h, int key, int val) — 0 on success, -1 if full.
  • int ht_get(const htab_t *h, int key, int *out) — 0 if found, -1 if not.

Use the hash ((unsigned)key * 2654435761u) % cap. Assume no key equals INT_MIN.

Starter code

#include <stdlib.h>
#include <string.h>
#include <stddef.h>

int  ht_init(htab_t *h, size_t cap){ /* TODO */ return -1; }
void ht_free(htab_t *h){ /* TODO */ }
int  ht_set(htab_t *h, int key, int val){ /* TODO */ return -1; }
int  ht_get(const htab_t *h, int key, int *out){ /* TODO */ return -1; }

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