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

Explain in simple terms how Hash Tables are implemented?

Câu trả lời

Hash tables are a fundamental data structure used to store key-value pairs efficiently. Here’s a simple explanation of how they are implemented:

Basic Concept

A hash table uses a hash function to map keys to specific indices in an array, where the corresponding values are stored. This allows for fast data retrieval, insertion, and deletion.

Steps to Implement a Hash Table

  1. Array Initialization:

    • A hash table starts with an array of a fixed size. Each position in the array is called a "bucket."
  2. Hash Function:

    • A hash function takes a key and converts it into an integer, which is then used to determine the index in the array where the value should be stored.
    • For example, a simple hash function might be hash = key % array_size.
  3. Storing Data:

    • When you want to store a key-value pair, the key is passed through the hash function to get an index.
    • The value is then stored at the computed index in the array.
  4. Handling Collisions:

    • Collisions occur when two different keys hash to the same index. There are several methods to handle collisions:
      • Separate Chaining: Each bucket in the array points to a linked list of entries that hash to the same index. If a collision occurs, the new entry is added to the linked list at that index.
      • Open Addressing: If a collision occurs, the algorithm searches for the next available slot in the array. Methods include linear probing (checking the next slot sequentially) and quadratic probing (checking slots at increasing intervals).

Example

Consider a hash table with an array size of 10 and a simple hash function hash = key % 10.

  • Insert (key, value):

    • Key: 15, Value: "A"
    • Hash function: 15 % 10 = 5
    • Store "A" at index 5.
  • Insert (key, value):

    • Key: 25, Value: "B"
    • Hash function: 25 % 10 = 5
    • Collision occurs (index 5 is already occupied).
    • Using separate chaining, add "B" to the linked list at index 5.

Pseudocode for Basic Operations

Insert Operation:

python Copy
def insert(key, value):
    index = hash_function(key)
    if array[index] is None:
        array[index] = [(key, value)]
    else:
        array[index].append((key, value))

Search Operation:

python Copy
def sear...
middle

middle

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

senior

Explain when to use Hashing on practice?

senior

What is the difference between HashMap and HashTable?

middle

What is MD5?

Bình luận

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

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