data-structures · intermediate · ~40 min
Hash table from scratch: hash function, chaining, deletion.
Implement a string-keyed, int-valued KV store with open chaining:
typedef struct kv kv_t;
kv_t *kv_create(int n_buckets);
void kv_set(kv_t *kv, const char *key, int value);
int kv_get(kv_t *kv, const char *key, int *out_value); /* 1=found,0=missing */
int kv_del(kv_t *kv, const char *key); /* 1=removed,0=missing */
void kv_destroy(kv_t *kv);
A key-value store is the universal data structure. Redis is a key-value store. Memcached is a key-value store. Browser localStorage is a key-value store. Building one from scratch reveals what hash maps actually buy you.
Lowercase ASCII keys, up to 64 bytes. Up to 10000 ops.
See API.
Use FNV-1a or djb2 for hashing. Use linked-list chains per bucket.
typedef struct kv kv_t;
kv_t *kv_create(int n_buckets);
void kv_set(kv_t *kv, const char *key, int value);
int kv_get(kv_t *kv, const char *key, int *out_value);
int kv_del(kv_t *kv, const char *key);
void kv_destroy(kv_t *kv);
Forgetting to update size on delete; comparing pointers instead of strcmp; not freeing key strdups on destroy.
Set then set on same key (update, no duplicate). Delete of missing key. Get of missing key.
Average O(1); worst-case O(n) with adversarial hash.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.