Hash Functions and Hash Tables Flashcards
Memorizing hash functions, their reason of being, and how to implement hash tables
What do they represent
Dynamic set of data
Which three functions do they support?
1) Insert
2) Search
3) Delete
What is the average runtime for their search operation?
O(1)
What is a dictionary in the world of code?
Generic way to map keys to values
What is a hash table
The implementation of a dictionary using a hash function
What is closed addressing/open hasing?
Where each slot in the table refers to a chain of entries, and each entry stores one (key, value) pair
What is open addressing/closed hasing?
Search for the next empty bucket within the hash table
What is the code to allocate a hash table and setting it’s elements to NULL?
dict_t *make_dictionary(void) {
dict_t *hashtable = malloc(sizeof(dict_t) * TABLESIZE);
assert(hashtable != NULL);
for (int i = 0; i < TABLESIZE; i++) {
hashtable[i] = NULL;
}
return hashtable;
}
What does the hash’s structure look like?
typedef struct entry {
char *key;
char *value; // value associated with the key
struct entry *next; // next entry in the linked list
} entry_t;
What is the run time to look up a value?
O(n)
What is the run time to look up a key?
O(1)
What is the code to print the contents of a dictionary?
void print_dictionary(dict_t *dict)
{
for (int bucket_index = 0; bucket_index < TABLESIZE; bucket_index++) {
printf(“%d: “, bucket_index);
entry_t *current_entry = dict[bucket_index];
if (current_entry == NULL) {
printf(“NULL\n”);
} else {
while (current_entry != NULL) {
printf(“%s: %s”, current_entry->key, current_entry->value);
current_entry = current_entry->next;
if (current_entry != NULL) {
printf(“, “);
}
}
printf(“\n”);
}
}
}
What is the code to be able to replace what is in a dictionary?
_Bool replace(dict_t *dict, char *key, char *value)
{
unsigned hash_index = hash(key);
entry_t *target_entry = search(dict[hash_index], key);
if (target_entry == NULL) {
return false;
} else {
free(target_entry->value);
target_entry->value = my_strdup(value);
assert(target_entry->value != NULL);
return true;
}
}
What is the code to clear a dictionary?
void clear(dict_t *dict)
{
for (int bucket_index = 0; bucket_index < TABLESIZE; bucket_index++) {
entry_t *current_entry = dict[bucket_index];
while (current_entry != NULL) {
entry_t *entry_to_free = current_entry;
current_entry = current_entry->next;
free(entry_to_free->key);
free(entry_to_free->value);
free(entry_to_free);
}
dict[bucket_index] = NULL;
}
}