Sobes.tech
Junior

What are the advantages of hash tables compared to arrays?

sobes.tech AI

Answer from AI

  • Fast search, insertion, and deletion of elements in average time O(1).
  • No need for pre-allocating fixed-size memory.
  • Ability to use not only numeric indices but also arbitrary hashable keys (strings, tuples, etc.).
# Example of search in a list (array) - O(n)
my_list = [10, 5, 8, 12, 3]
if 8 in my_list:
    print("Found")

# Example of search in a dictionary (hash table) - O(1) on average
my_dict = {1: 10, 2: 5, 3: 8, 4: 12, 5: 3}
if 3 in my_dict:
    print("Found")
Operation Hash table (average) Array (list in Python)
Access O(1) O(1) by index
Search O(1) O(n)
Insertion O(1) O(n) (middle/start), O(1) (end)
Deletion O(1) O(n)