GOAL
The goal is to use a chained hash table, with a hashing function h that satisfies the Simple Uniform Hashing Assumption, to store some numbers (the same number, if inserted multiple times, is stored multiple times in the linked list associated with h(n)). We have 3 functions to implement: one that inserts a new number n and counts the number of occurrences of the number, one that deletes a number and counts the number of occurrences of the number and one that just counts the number of occurrences of the number.
NOTES
We have to use pseudocode (similar to python) and can use method ".head" that returns the head of the linked list and the functions LIST_PREPEND, LIST_SEARCH that prepend an item (given as a pointer) and search a key (returning the associated pointer) in the linked list. We can also use CHAINED_HASH_DELETE which deletes an item (given as a pointer) from the linked list associated to it. Note that the variable x always denotes a pointer to an item in one of the linked lists of the hash table, n is always an integer, which we use as key, and M is the chained hash table. The syntax and ""programming"" really don't matter, what matters is the algorithm.
MY CODE
COUNT(M, n):
count = 0
x = M[h(n)].head
if x == NIL: #the linked list is empty
return 0
else:
while x != NIL: #search the list until its end
if x.key == n:
count = count + 1
x = x.next
return count
DELETE(M, n)
x = LIST_SEARCH(M[h(n)], n)
CHAINED_HASH_DELETE(M, x)
COUNT(M, n)
INSERT(M, n):
<let x be a pointer to n>
LIST_PREPEND(M[h(n)], x)
COUNT(M, n)
MY QUESTION
The idea behind my code is probably a little bit inefficient because every time I have to re-count the number of occurrences. But, the average complexity of all the functions (COUNT, INSERT, DELETE) the should anyway be O(1+a) where a is the load factor, because LIST_SEARCH and COUNT have complexity O(1+a). Is the average complexity correct? Are the algorithms themselves correct?
Another solution was to use an attribute .counter on the first item of the linked list in M[h(n)] and add 1 or subtract 1 each time I insert or delete an item. Since the resulting complexities are also O(1+a) because I have to find the first item equal to n, it shouldn't matter a lot in a theoretical scenario, correct?