Sobes.tech
Junior — Middle

Explain the working principle of a hash table and why it is used in programming.

sobes.tech AI

Answer from AI

A hash table is a data structure that provides fast access to elements by key. It works based on computing a hash function from the key, which transforms the key into an array index where the value is stored.

Working principle:

  1. A hash code is computed for the given key.
  2. The hash code is transformed into an array index (usually modulo the array size).
  3. The value or list of values is stored at this index (in case of collisions).

Uses:

  • Fast search, insertion, and deletion of elements — on average in O(1).
  • Efficient storage of key-value pairs.

Example in C++ using std::unordered_map:

#include <iostream>
#include <unordered_map>

int main() {
    std::unordered_map<std::string, int> map;
    map["apple"] = 5;
    map["banana"] = 3;

    std::cout << "apple: " << map["apple"] << std::endl;
    return 0;
}
Explain the working principle of a hash table and why… - sobes.tech