From ab57931249d7175bb98d619a657d103e9e3adb3e Mon Sep 17 00:00:00 2001 From: john-the-dev <52230987+john-the-dev@users.noreply.github.com> Date: Thu, 10 Sep 2020 01:51:02 -0700 Subject: [PATCH] Reduce remove cost from O(n) to O(1) Exchange the item with the last item in the array and then pop it. --- solutions/object_oriented_design/hash_table/hash_map.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/solutions/object_oriented_design/hash_table/hash_map.py b/solutions/object_oriented_design/hash_table/hash_map.py index 33d9a35d..d90a2743 100644 --- a/solutions/object_oriented_design/hash_table/hash_map.py +++ b/solutions/object_oriented_design/hash_table/hash_map.py @@ -33,6 +33,7 @@ class HashTable(object): hash_index = self._hash_function(key) for index, item in enumerate(self.table[hash_index]): if item.key == key: - del self.table[hash_index][index] + self.table[hash_index][index],self.table[hash_index][-1] = self.table[hash_index][-1],self.table[hash_index][index] + self.table[hash_index].pop() return raise KeyError('Key not found')