Câu hỏi phỏng vấn Hash Tables
Câu hỏi

Provide a simple example of Hash Function

Câu trả lời

A hash function is a crucial component of a hash table, which maps data of arbitrary size to fixed-size values, typically integers, that represent the indices in an array where the data is stored. Here is a simple example of a hash function using the modulo operation:

Example of a Simple Hash Function

Consider a hash table of size 10. We can use a simple hash function that takes an integer key and returns an index by computing the remainder of the key divided by the size of the hash table. This is known as the division method.

Hash Function Definition

h(k) = k \mod \text{table\_size}

Example Implementation in Python

# Define the size of the hash table
SIZE = 10

# Define a simple hash function using the modulo operator
def hash_function(key):
    return key % SIZE

# Example keys to be hashed
keys = [15, 25, 35, 45]

# Compute and print the hash values for the keys
for key in keys:
    print(f"Key: {key}, Hash: {hash_function(key)}")

Output

Key: 15, Hash: 5
Key: 25, Hash: 5
Key: 35, Hash: 5
Key: 45, Hash: 5

Explanation

  1. Hash Function: The function hash_function(key) computes the hash value by taking the key modulo the size of the hash table (key % SIZE).
  2. Keys: The example uses keys 15, 25, 35, and 45.
  3. Hash Values: For each key, the hash function computes the index where the key should be stored in the hash table. In this case, all keys hash to the same index (5), demonstrating a collision.

Handling Collisions

Collisions occur when multiple keys hash to the same index. One common method to handle collisions is linear probing, where you sequentially check the next available slot in the array.

Example of Linear Probing

# Initialize the hash table with None values
hash_table = [None] * SIZE

# Insert function with linear probing
def insert(key):
    index = hash_function(key)
    while ha...
junior

junior

Gợi ý câu hỏi phỏng vấn

middle

How can Hash Functions be used to perform lookups?

junior

Define what is a Hash Function?

junior

Explain what is Hash Value?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào