data-structures-algorithms-python icon indicating copy to clipboard operation
data-structures-algorithms-python copied to clipboard

Hashtable - Linear probing __setitem__ not considering updates.

Open ManuMathewVarghese opened this issue 2 years ago • 0 comments

Case: Key exists after the first empty slot. Issue: Code inserts the new (key,value) instead of updating existing (key,value).

Code in question:
def find_slot(self, key, index):
        prob_range = self.get_prob_range(index)
        for prob_index in prob_range:
            if self.arr[prob_index] is None:
                return prob_index
            if self.arr[prob_index][0] == key:
                return prob_index
        raise Exception("Hashmap full") ```
Maybe this can fix it:
def find_slot(self, key, index):
        first_slot = None
        prob_range = self.get_prob_range(index)
        for prob_index in prob_range:
            if first_slot == None and self.arr[prob_index] is None:
                first_slot = prob_index
            if self.arr[prob_index][0] == key:
                return prob_index
        if first_slot is not None:
           return first_slot
        raise Exception("Hashmap full")

ManuMathewVarghese avatar Jun 28 '23 02:06 ManuMathewVarghese