---
title: "Hash Tables: How Hashing Gives O(1) Lookups"
url: https://khanwaseem.com/blog/data-structure-and-algorithm/hash-table-data-structure
author: "khan Waseem"
published: 2026-11-22
updated: 2026-11-22
topics: ["Data Structure and Algorithm", "Blog"]
description: "How a hash table turns a key into an array index, what happens when two keys collide, why the table resizes itself, and how to use JavaScript’s Map and Set to solve real problems in O(1) time."
---

# Hash Tables: How Hashing Gives O(1) Lookups

Table of Contents

[Toggle](#)

- [Introduction:](#introduction)
- [What Is a Hash Table?](#what-is-a-hash-table)
- [The Hash Function](#the-hash-function)
- [Collisions](#collisions)[1. Separate Chaining:](#1-separate-chaining)
- [2. Open Addressing:](#2-open-addressing)

- [Load Factor and Resizing](#load-factor-and-resizing)
- [Building a Hash Table in JavaScript](#building-a-hash-table-in-javascript)
- [Time Complexity](#time-complexity)
- [Hash Tables in JavaScript: Map, Set and Objects](#hash-tables-in-javascript-map-set-and-objects)
- [Solving Problems with Hash Tables](#solving-problems-with-hash-tables)[1. Two Sum:](#1-two-sum)
- [2. First Repeated Character:](#2-first-repeated-character)
- [3. Counting Words:](#3-counting-words)

- [Where Hash Tables Are Used](#where-hash-tables-are-used)
- [Conclusion:](#conclusion)

## Introduction:

Suppose you have a list of one million users and you want to find the user whose email is `sara@example.com`. With an array you would have to check the users one by one, which is O(n). With a sorted array and binary search you could do it in O(log n). A **hash table** does it in **O(1)** on average: it jumps almost straight to the right place, no matter how many users there are.

Hash tables are everywhere. JavaScript objects, `Map` and `Set`, Python dictionaries, Java’s `HashMap`, database indexes and caches such as Redis are all built on the same idea. In this lesson we will see how that idea works, build a small hash table ourselves, and then use one to solve some classic problems.

## What Is a Hash Table?

A hash table stores **key-value pairs**. You give it a key (a username, an email, a product ID) and it gives you back the value stored with that key.

Inside, a hash table is just an **array**. The trick is how it decides which slot of the array a key goes into. It passes the key through a **hash function**, which turns the key into a number, and then uses that number as the index.

```javascript
key "apple"  -> hash("apple")  -> 5  -> buckets[5] = ["apple", 120]
key "banana" -> hash("banana") -> 2  -> buckets[2] = ["banana", 40]Code language: JavaScript (javascript)
```

To read `"apple"` later, the table hashes `"apple"` again, gets 5 again, and looks directly at slot 5. There is no searching.

## The Hash Function

A good hash function has three properties:

- **Deterministic:** the same key always gives the same number. Otherwise you could never find the key again.

- **Fast:** it is run on every insert and every lookup, so it must be cheap.

- **Spreads keys evenly:** similar keys such as `"user1"` and `"user2"` should land in very different slots, so that no slot gets crowded.

Here is a simple string hash function (a version of the well-known djb2 hash). It walks through the characters, mixes each character code into a running number, and finally uses the remainder (`%`) to fit the number into the size of the array:

```javascript
function hash(key, size) {
  let h = 5381;
  for (let i = 0; i < key.length; i++) {
    h = (h * 33 + key.charCodeAt(i)) >>> 0; // keep it a 32-bit unsigned number
  }
  return h % size;
}Code language: JavaScript (javascript)
```

## Collisions

An array has a limited number of slots, but there are endless possible keys. Sooner or later two different keys will get the same index. This is called a **collision**, and every hash table must handle it. There are two common strategies.

### 1. Separate Chaining:

Each slot (called a **bucket**) holds a small list. Keys that collide are simply stored together in the same list. To find a key, you hash it to get the bucket and then search that short list.

```css
buckets[0] -> []
buckets[1] -> [["mango", 150]]
buckets[2] -> [["banana", 40], ["grape", 90]]   <- collision, both live here
buckets[3] -> []Code language: CSS (css)
```

### 2. Open Addressing:

Every slot holds at most one entry. When the slot for a key is already taken, the table tries the next slot (this is called **linear probing**), and the next, until it finds an empty one. Lookups follow the same path. Open addressing uses memory well but becomes slow when the table gets full.

Java’s `HashMap` uses chaining, while Python’s `dict` uses open addressing. Both work well when the table is kept from getting too full.

## Load Factor and Resizing

The **load factor** is the number of stored entries divided by the number of buckets. If a table with 8 buckets holds 6 entries, its load factor is 0.75.

As the load factor grows, collisions become more common and the buckets’ lists get longer, so lookups slow down. To prevent this, a hash table **resizes** itself: when the load factor passes a limit (0.75 is a common choice), it creates a bigger array, usually twice the size, and re-inserts every entry. Each key must be re-hashed because its index depends on the array size.

Resizing costs O(n), but it happens rarely, and each time the table doubles. Spread over all the inserts, the average cost per insert stays O(1). This is called **amortized O(1)**.

## Building a Hash Table in JavaScript

Let’s put it all together: a hash function, separate chaining for collisions, and automatic resizing.

```javascript
class HashTable {
  constructor(capacity = 8) {
    this.buckets = new Array(capacity).fill(null).map(() => []);
    this.size = 0;
  }

  // Turn a string key into a bucket index (djb2-style hash).
  hash(key) {
    let h = 5381;
    for (let i = 0; i < key.length; i++) {
      h = (h * 33 + key.charCodeAt(i)) >>> 0;
    }
    return h % this.buckets.length;
  }

  set(key, value) {
    const bucket = this.buckets[this.hash(key)];
    const entry = bucket.find((e) => e[0] === key);
    if (entry) {
      entry[1] = value; // key exists: update it
      return;
    }
    bucket.push([key, value]);
    this.size++;
    if (this.size / this.buckets.length > 0.75) this.resize();
  }

  get(key) {
    const bucket = this.buckets[this.hash(key)];
    const entry = bucket.find((e) => e[0] === key);
    return entry ? entry[1] : undefined;
  }

  has(key) {
    return this.get(key) !== undefined;
  }

  delete(key) {
    const bucket = this.buckets[this.hash(key)];
    const i = bucket.findIndex((e) => e[0] === key);
    if (i === -1) return false;
    bucket.splice(i, 1);
    this.size--;
    return true;
  }

  resize() {
    const old = this.buckets;
    this.buckets = new Array(old.length * 2).fill(null).map(() => []);
    this.size = 0;
    for (const bucket of old) {
      for (const [key, value] of bucket) this.set(key, value);
    }
  }
}Code language: JavaScript (javascript)
```

Now let’s use it:

```javascript
const prices = new HashTable();
prices.set("apple", 120);
prices.set("banana", 40);
prices.set("mango", 150);
prices.set("apple", 110); // update

console.log(prices.get("apple"));     // 110
console.log(prices.has("grape"));     // false
console.log(prices.delete("banana")); // true
console.log(prices.size);             // 2

// Resizing keeps every key reachable
const t = new HashTable(2);
for (let i = 0; i < 100; i++) t.set("key" + i, i);
console.log(t.size, t.buckets.length, t.get("key57")); // 100 256 57Code language: JavaScript (javascript)
```

The last example starts with only 2 buckets. As 100 keys are added, the table doubles several times until it has 256 buckets, and every key can still be found.

## Time Complexity

- **Insert, lookup, delete (average):** O(1). The hash points straight to a bucket that holds only a few entries.

- **Insert, lookup, delete (worst case):** O(n). If the hash function is bad, or an attacker picks keys on purpose, every key can land in the same bucket, and the table becomes a slow list.

- **Space:** O(n).

Hash tables also do **not** keep keys in sorted order. If you need “all keys between A and F” or “the smallest key”, a balanced binary search tree is the better choice, as we saw in the binary search tree lesson.

## Hash Tables in JavaScript: Map, Set and Objects

You will rarely write your own hash table in real code. JavaScript already gives you three:

- **`Map`** stores key-value pairs. Keys can be any type (numbers, objects, functions), it remembers insertion order, and it has a `size` property. Use it whenever you need a dictionary.

- **`Set`** stores unique values only, with fast `has()` checks. Use it to remove duplicates or to remember what you have already seen.

- **Plain objects** also work as dictionaries, but their keys are always turned into strings, and they inherit properties such as `toString` from their prototype.

```javascript
const obj = {};
obj[1] = "one";
console.log(Object.keys(obj)); // [ '1' ]  <- the number became a string

const map = new Map();
map.set(1, "one");
console.log([...map.keys()]);  // [ 1 ]    <- the number stays a numberCode language: JavaScript (javascript)
```

## Solving Problems with Hash Tables

Many interview problems become easy once you think “I can remember things in a hash table”. The pattern is always the same: trade a little memory for a big gain in speed.

### 1. Two Sum:

Given an array of numbers and a target, find the indexes of two numbers that add up to the target. Checking every pair takes O(n²). With a `Map` we walk the array once, and for each number we ask: “have I already seen the number that completes this pair?”

```javascript
function twoSum(nums, target) {
  const seen = new Map(); // value -> index
  for (let i = 0; i < nums.length; i++) {
    const need = target - nums[i];
    if (seen.has(need)) return [seen.get(need), i];
    seen.set(nums[i], i);
  }
  return null;
}

console.log(twoSum([2, 7, 11, 15], 9)); // [ 0, 1 ]
console.log(twoSum([3, 2, 4], 6));      // [ 1, 2 ]Code language: JavaScript (javascript)
```

This runs in O(n) time and O(n) space.

### 2. First Repeated Character:

```javascript
function firstRepeatedChar(str) {
  const seen = new Set();
  for (const ch of str) {
    if (seen.has(ch)) return ch;
    seen.add(ch);
  }
  return null;
}

console.log(firstRepeatedChar("programming")); // rCode language: JavaScript (javascript)
```

### 3. Counting Words:

```javascript
function wordCount(text) {
  const counts = new Map();
  for (const word of text.toLowerCase().split(/\W+/).filter(Boolean)) {
    counts.set(word, (counts.get(word) || 0) + 1);
  }
  return counts;
}

console.log(wordCount("the cat and the hat"));
// Map(4) { 'the' => 2, 'cat' => 1, 'and' => 1, 'hat' => 1 }Code language: JavaScript (javascript)
```

## Where Hash Tables Are Used

- **Caches:** Redis and in-memory caches look up data by key in O(1).

- **Database indexes:** hash indexes find a row by its exact key without scanning the table.

- **Deduplication:** checking whether a URL was already crawled or an email already registered.

- **Counting and grouping:** word frequencies, votes, or grouping orders by customer.

- **Compilers and interpreters:** symbol tables map variable names to their values and types.

## Conclusion:

A hash table turns a key into an array index with a hash function, so it can store and find data in O(1) time on average. Collisions are handled with chaining or open addressing, and resizing keeps the load factor low so lookups stay fast. In JavaScript you get all of this for free with `Map` and `Set`. Whenever a solution checks “have I seen this before?” inside a loop, a hash table can usually turn an O(n²) algorithm into an O(n) one.

In the next lesson we will look at **recursion**, the technique behind tree traversals, divide-and-conquer sorting and dynamic programming.

### Related posts:

[CSS – Table](https://blog.khanwaseem.com/css-table/)
[HTML – Tables](https://blog.khanwaseem.com/html-tables/)
[JavaScript – Arrays](https://blog.khanwaseem.com/javascript-arrays/)
[Lists and Keys](https://blog.khanwaseem.com/lists-and-keys/)

Powered by [YARPP](https://yarpp.com).
