Step 5 of 5

100% Complete

Applications of Hash Tables

Explore real-world use cases and implementations of hash tables

Common Applications of Hash Tables

Hash tables are one of the most versatile and widely used data structures in computer science. Their ability to provide fast lookups, insertions, and deletions makes them ideal for many applications:

1. Database Indexing

Hash tables are used to create indexes in databases, allowing for quick lookups of records by specific fields.

// Simplified example of a database index using a hash table
class DatabaseIndex {
constructor() {
this.index = new Map(); // JavaScript's built-in hash table
}
// Add a record to the index
addRecord(key, recordId) {
if (!this.index.has(key)) {
this.index.set(key, []);
}
this.index.get(key).push(recordId);
}
// Find records by key
findRecords(key) {
return this.index.has(key) ? this.index.get(key) : [];
}
}

2. Caching

Hash tables are used to implement caches, storing recently accessed or computed data for quick retrieval.

// Simple LRU Cache implementation using a hash table
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.cache = new Map(); // For O(1) lookups
}
get(key) {
if (!this.cache.has(key)) return -1;
// Update access order by removing and re-adding
const value = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, value);
return value;
}
put(key, value) {
// Remove the key to update access order
if (this.cache.has(key)) {
this.cache.delete(key);
}
// Evict the least recently used item if at capacity
else if (this.cache.size >= this.capacity) {
const oldestKey = this.cache.keys().next().value;
this.cache.delete(oldestKey);
}
this.cache.set(key, value);
}
}

3. Symbol Tables in Compilers

Compilers and interpreters use hash tables to store information about variables, functions, and other symbols.

// Simplified symbol table for a compiler
class SymbolTable {
constructor() {
this.symbols = new Map();
this.scopes = []; // Stack of scopes
this.currentScope = 0;
}
enterScope() {
this.scopes.push(this.currentScope);
this.currentScope = this.symbols.size;
}
exitScope() {
// Remove all symbols added in the current scope
for (let i = this.currentScope; i < this.symbols.size; i++) {
const key = Array.from(this.symbols.keys())[i];
this.symbols.delete(key);
}
this.currentScope = this.scopes.pop();
}
define(name, type, value) {
const key = `${name}@${this.currentScope}`;
this.symbols.set(key, { type, value });
}
lookup(name) {
// Look for the symbol in the current scope and all parent scopes
for (let scope = this.currentScope; scope >= 0; scope--) {
const key = `${name}@${scope}`;
if (this.symbols.has(key)) {
return this.symbols.get(key);
}
}
return null; // Symbol not found
}
}

4. Implementing Sets and Maps

Hash tables are the underlying data structure for implementing sets and maps in many programming languages.

// JavaScript's built-in Set and Map are implemented using hash tables
const set = new Set(); // A collection of unique values
set.add('apple');
set.add('banana');
set.add('apple'); // Duplicate, won't be added
console.log(set.has('apple')); // true
console.log(set.size); // 2
const map = new Map(); // A collection of key-value pairs
map.set('name', 'John');
map.set('age', 30);
console.log(map.get('name')); // 'John'
console.log(map.has('email')); // false

5. Counting Frequencies

Hash tables are excellent for counting the frequency of items in a collection.

// Count word frequencies in a text
function countWordFrequencies(text) {
const words = text.toLowerCase().match(/\w+/g) || [];
const frequencies = new Map();
for (const word of words) {
frequencies.set(word, (frequencies.get(word) || 0) + 1);
}
return frequencies;
}
const text = "To be or not to be, that is the question.";
const wordFreq = countWordFrequencies(text);
console.log(wordFreq); // Map { 'to' => 2, 'be' => 2, 'or' => 1, 'not' => 1, ... }

6. De-duplication

Hash tables can efficiently remove duplicates from a collection by storing only unique values.

// Remove duplicates from an array
function removeDuplicates(array) {
return [...new Set(array)];
}
const numbers = [1, 2, 3, 2, 1, 4, 5, 4, 3];
console.log(removeDuplicates(numbers)); // [1, 2, 3, 4, 5]

7. Two-Sum Problem

Hash tables are used to solve the classic "Two-Sum" problem efficiently.

// Find two numbers in an array that add up to a target
function twoSum(nums, target) {
const numMap = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (numMap.has(complement)) {
return [numMap.get(complement), i];
}
numMap.set(nums[i], i);
}
return null; // No solution found
}
const nums = [2, 7, 11, 15];
const target = 9;
console.log(twoSum(nums, target)); // [0, 1] (2 + 7 = 9)

Hash Tables in Different Languages

Many programming languages provide built-in hash table implementations:

JavaScript

  • Map - Key-value pairs with any type of keys
  • Set - Collection of unique values
  • Object - Simple key-value store with string/symbol keys

Python

  • dict - Dictionary for key-value pairs
  • set - Collection of unique values
  • collections.defaultdict - Dictionary with default values for missing keys
  • collections.Counter - Dictionary for counting hashable objects

Java

  • HashMap - General-purpose map implementation
  • HashSet - Set implementation backed by a hash table
  • LinkedHashMap - Hash map that maintains insertion order
  • ConcurrentHashMap - Thread-safe hash map

C++

  • std::unordered_map - Hash table implementation of map
  • std::unordered_set - Hash table implementation of set
  • std::unordered_multimap - Hash table with multiple values per key

Advanced Hash Table Concepts

As you continue to work with hash tables, you may encounter these advanced concepts:

Perfect Hashing

A technique that guarantees no collisions, typically used when the set of keys is known in advance.

Consistent Hashing

A technique used in distributed systems to minimize rehashing when the number of slots changes.

Cuckoo Hashing

A technique that uses multiple hash functions and guarantees O(1) worst-case lookup time.

Bloom Filters

A space-efficient probabilistic data structure that uses hash functions to test whether an element is a member of a set.

Practice Exercises

Test your understanding of hash table applications with these interactive exercises:

Congratulations!

You've completed the Hash Table tutorial! You now understand:

  • What hash tables are and how they work
  • How to implement insert, delete, and search operations
  • Common applications and use cases for hash tables
  • Advanced concepts and variations of hash tables

Hash tables are one of the most important data structures in computer science, and understanding them well will help you solve many programming problems efficiently.