AlgoTales · Roadmap

Hashing

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Hashing turns a value (a word, email, ID) into a number that points straight to a storage slot, so you can check "have I seen this?" in one step instead of searching through everything. It is why lookups in dictionaries, caches and databases feel instant.

Practical use cases

  • Web app: Rejecting duplicate sign-ups. A registration form must tell a user at once that an email is already taken. Searching 2 million users one by one is slow. Keeping emails in a hash-based set or a database index answers yes or no in one lookup.
  • Web app: Caching expensive page results. A Laravel or PHP site stores the rendered result of a heavy product page in a cache under a key such as the page address. The next visitor gets it by key lookup, and the page drops from 2 seconds to a few milliseconds.
  • Web app: Counting words or finding anagrams. A blog tool counts how often each word appears, or groups words that are anagrams. Using a PHP array or JavaScript Map keyed by word (or sorted letters) gives counts in a single pass. Counts are ready after a single read of the text, even for a long article.
  • System: Database indexes and spam filters. Databases use hash lookups for exact matches, and spam or duplicate-upload checks keep fingerprints of what they have seen already. This is why exact-match searches feel instant even on huge tables.

The story: The Cloakroom Token Wall

At the big mela, Aarav ran the cloakroom. Hundreds of bags came in, and visitors came back asking, "Do you have my bag, number 482?" At first he searched the whole shelf each time. By evening the queue stretched to the river.

Then Mrs. Sharma helped him fix a token wall: a board with a hook for every token number. Bag 482 goes on hook 482. Now "do you have bag 482?" takes one glance at one hook. No searching.

Later the mela committee asked a puzzle: "In the jumbled token numbers 100, 4, 200, 1, 3, 2, what is the longest run of back-to-back numbers?" Aarav smiled. With the token wall he asks "is the number just before this one on the wall?" If not, this number starts a run, and he counts upward by asking the wall each time.

The smell of hashing: "have I seen this before?", "does it exist?", "count how many", "pair that adds up", and you are tempted to nest two loops. Replace the inner loop with a one-glance lookup in a hash set or map.

How to spot this problem, and where you need it

You keep searching through a big list to see whether something exists or to count occurrences, and the search gets slower as the list grows.

Signs you need it

  • You use in_array(), array_search(), or includes() inside a loop, so the work multiplies as the data grows.
  • The question is "have I seen this before?", "find duplicates", "count how many of each", or "find two items that add up to X".
  • A page is fast with test data but slow with real data, with a lookup inside a loop as the cause.

Where to use it in a project

  • Duplicate checks on sign-ups, uploads and imports where "does this already exist" is asked.
  • Caches keyed by a page address, user id or query, so repeated requests are served fast.
  • Grouping and counting records by a key in reports, such as orders per city.

The solution

Store items in a hash-based structure (PHP associative array, JavaScript Map or Set, database unique index) where the value itself decides which slot it lives in. To check existence or fetch a count, compute the slot from the value and look only there. Insert as you go along, so a single pass over the data answers questions that used to need a loop inside a loop.

Payoff: Before: 2 million comparisons for each check. After: one lookup, effectively instant.

Explain it like I am 8

You have a wall of cubby holes, one for each number. To check whether a number is in your pile, you do not dig through the pile. You just peek into that number's cubby hole: full or empty, instantly.

How it works, step by step

  1. Clues: "have we seen", "duplicate", "count occurrences", "does it exist", "two numbers that add to x", "group by". Think hashing.
  2. Put everything into a set or map first (or as you go). Now "is x here?" costs about one step.
  3. Find the inner loop in your slow idea ("scan the whole array for ..."). Replace it with a lookup.
  4. For the longest run: only start counting from numbers whose n - 1 is not in the set. Those are run starts.
  5. Count upward from each start asking the set n + 1, n + 2... Every number is counted in at most one run, so the total work is linear.

The code in four languages

PHP

<?php
// Longest Consecutive Sequence: hash set so "is n-1 present?" is one step
function longestRun(array $nums): int {
    $set = array_flip($nums);            // numbers become keys: instant lookup
    $best = 0;
    foreach (array_keys($set) as $n) {
        if (isset($set[$n - 1])) {
            continue;                    // not a start: a smaller neighbour exists
        }
        $len = 1;
        while (isset($set[$n + $len])) { // walk up the run
            $len++;
        }
        $best = max($best, $len);
    }
    return $best;
}
echo longestRun([100, 4, 200, 1, 3, 2]);   // 4  (1, 2, 3, 4)

JavaScript

// Longest Consecutive Sequence: hash set so "is n-1 present?" is one step
function longestRun(nums) {
  const set = new Set(nums);             // instant lookup, duplicates vanish
  let best = 0;
  for (const n of set) {
    if (set.has(n - 1)) {
      continue;                          // not a start: a smaller neighbour exists
    }
    let len = 1;
    while (set.has(n + len)) {           // walk up the run
      len++;
    }
    best = Math.max(best, len);
  }
  return best;
}
console.log(longestRun([100, 4, 200, 1, 3, 2]));   // 4  (1, 2, 3, 4)

Java

import java.util.*;

public class Main {
    // Longest Consecutive Sequence: hash set so "is n-1 present?" is one step
    static int longestRun(int[] nums) {
        Set<Integer> set = new HashSet<>();      // instant lookup, duplicates vanish
        for (int x : nums) set.add(x);
        int best = 0;
        for (int n : set) {
            if (set.contains(n - 1)) {
                continue;                        // not a start: a smaller neighbour exists
            }
            int len = 1;
            while (set.contains(n + len)) {      // walk up the run
                len++;
            }
            best = Math.max(best, len);
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(longestRun(new int[]{100, 4, 200, 1, 3, 2}));   // 4  (1, 2, 3, 4)
    }
}

Go

package main

import "fmt"

// longestRun is Longest Consecutive Sequence: a hash set so "is n-1 present?" is one step.
func longestRun(nums []int) int {
	set := map[int]bool{} // instant lookup, duplicates vanish
	for _, x := range nums {
		set[x] = true
	}
	best := 0
	for n := range set {
		if set[n-1] {
			continue // not a start: a smaller neighbour exists
		}
		length := 1
		for set[n+length] { // walk up the run
			length++
		}
		best = max(best, length)
	}
	return best
}

func main() {
	fmt.Println(longestRun([]int{100, 4, 200, 1, 3, 2})) // 4  (1, 2, 3, 4)
}

Time: O(n) · Extra space: O(n). Each number is part of only one counted run, and each lookup is about one step; the set costs memory for all n numbers.

Watch out for

  • Counting upward from every number, not only run starts. That quietly becomes O(n²) on long runs.
  • Sorting first "to make it easy". It works but costs O(n log n), and the problem often asks for O(n).
  • Assuming a hash lookup is always free. Bad hash functions or huge keys can slow it down.

Quick check

  1. You catch yourself writing a loop inside a loop just to ask "have I seen this?". Which pattern?
    • Fast/slow pointers
    • Two pointers
    • Hashing
  2. Why only start counting from numbers whose n-1 is missing?
    • To save memory
    • Because sets are sorted
    • So each run is counted exactly once, from its beginning
  3. Cost of "is x in the set?" on average?
    • O(n)
    • About O(1)
    • O(log n)