AlgoTales · Roadmap

HashMap / HashSet

Beginner · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A HashMap stores pairs, like a label and its value, and finds a value instantly from its label. A HashSet stores only labels, so you can ask "is this here?" instantly and each item appears only once. They are the everyday tools behind speedy lookups.

Practical use cases

  • Web app: Remove duplicate emails from an import. An admin uploads a CSV of 50,000 newsletter contacts with many repeated emails. Instead of comparing every row against every other row, the code adds each email to a set and skips it if already there. The import finishes in a second and nobody gets the newsletter twice.
  • Web app: Cache of product details. A product page needs a product row from the database every time. Keeping a map from product id to its data in memory means repeat visitors get the answer without another query. A popular product drops from a database trip each time to one instant lookup.
  • Web app: Group orders by customer. A report must show total spend per customer from a list of 100,000 orders. A map from customer id to running total lets the code add each order in one step. No nested loops are needed, and the report builds in the time of one pass.
  • System: Web crawler visited list. A crawler remembers every page address it has visited in a set, so it never fetches the same page twice. Without that memory, two pages linking to each other would send it round in circles forever, wasting bandwidth and hammering other websites with repeat requests.

The story: The Phone Book and the Guest Register

Grandpa Bhaskar kept two things on his desk. The first was his thick phone book: every name had a number beside it. The second was the visitor register at the gate of his society: only names, one line each, and a rule that no name was written twice, however many times the person visited.

Mira noticed something. "Dadaji, for the phone book you ask "what is Mrs. Iyer's number?" and for the register you ask "has Mrs. Iyer visited?". They are different questions." Grandpa nodded. "One answers with a value, the other with just yes or no."

She told him that his desk matched two tools programmers use every day. The phone book is a HashMap (also called dictionary, associative array or object): key → value. The register is a HashSet: just keys, no duplicates. Both are built on a hash table, so both answer in about one step even with a million names. "Then why does my phone book take me forever?" Grandpa laughed. "Because it is paper, not hashed!"

How to spot this problem, and where you need it

You keep looping through a list to check if something exists or to find the value that belongs to a name or id, and it gets slower as the list grows.

Signs you need it

  • You write in_array(), array_search(), includes() or indexOf() inside a loop, which means a loop inside a loop.
  • The problem says "unique", "duplicate", "seen before", "count occurrences" or "group by".
  • You are repeatedly asking "what is the data for this id?" and scanning a list to answer.
  • A page or script is fast with 100 rows but takes many seconds with 50,000.

Where to use it in a project

  • Building lookup tables once, such as product id to row, then reading them while rendering a page or report.
  • De-duplicating imports, tracking visited items, and keeping per-user or per-category totals.

The solution

Use a map when each label has data, and a set when you only need to know presence. Fill it in one pass: for each item, store it under its key. After that, every question becomes a direct lookup by key instead of a search through the whole list. In PHP that is an associative array, in JavaScript a Map or Set, in Python a dict or set.

Payoff: Before: 50,000 x 50,000 comparisons, minutes of waiting. After: 50,000 quick lookups, finishing in a fraction of a second.

Explain it like I am 8

A HashMap is a toy box with labels: ask for "red car" and get the red car. A HashSet is a guest list: you can only check whether a name is on it, and a name can appear only once.

How it works, step by step

  1. HashMap: set(key, value) stores a pair; setting an existing key replaces its value.
  2. get(key) returns the value (or nothing if the key is missing), and has(key) tells you whether the key exists.
  3. HashSet: add(x) stores a value; adding it twice leaves just one copy.
  4. has(x) answers "is x in the set?" in about one step. delete(x) removes it.
  5. In PHP, use an array ($map[$key] = $value), and for a set store the values as keys. In JavaScript, use Map and Set.

The code in four languages

PHP

<?php
// HashMap: PHP arrays are hash tables (key => value)
$marks = [];
$marks['Raju'] = 12;
$marks['Mira'] = 9;
$marks['Raju'] = 15;                         // same key: value replaced
echo 'Raju: ' . $marks['Raju'] . "\n";       // 15
echo 'Has Mira? ' . (isset($marks['Mira']) ? 'yes' : 'no') . "\n";
unset($marks['Mira']);                        // delete
echo 'Has Mira? ' . (isset($marks['Mira']) ? 'yes' : 'no') . "\n";

// HashSet: keep the values as keys, so each appears once
$visitors = [];
foreach (['Zoya', 'Aarav', 'Zoya'] as $name) $visitors[$name] = true;
echo 'Unique visitors: ' . count($visitors) . "\n";                 // 2
echo 'Visited? ' . (isset($visitors['Aarav']) ? 'yes' : 'no') . "\n";   // yes

JavaScript

// HashMap: the built-in Map (key => value)
const marks = new Map();
marks.set('Raju', 12);
marks.set('Mira', 9);
marks.set('Raju', 15);                       // same key: value replaced
console.log('Raju: ' + marks.get('Raju'));   // 15
console.log('Has Mira? ' + (marks.has('Mira') ? 'yes' : 'no'));
marks.delete('Mira');                        // delete
console.log('Has Mira? ' + (marks.has('Mira') ? 'yes' : 'no'));

// HashSet: the built-in Set keeps each value once
const visitors = new Set();
for (const name of ['Zoya', 'Aarav', 'Zoya']) visitors.add(name);
console.log('Unique visitors: ' + visitors.size);                          // 2
console.log('Visited? ' + (visitors.has('Aarav') ? 'yes' : 'no'));          // yes

Java

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // HashMap: key => value
        Map<String, Integer> marks = new HashMap<>();
        marks.put("Raju", 12);
        marks.put("Mira", 9);
        marks.put("Raju", 15);                                  // same key: value replaced
        System.out.println("Raju: " + marks.get("Raju"));       // 15
        System.out.println("Has Mira? " + (marks.containsKey("Mira") ? "yes" : "no"));
        marks.remove("Mira");                                   // delete
        System.out.println("Has Mira? " + (marks.containsKey("Mira") ? "yes" : "no"));

        // HashSet: keeps each value once
        Set<String> visitors = new HashSet<>();
        for (String name : new String[]{"Zoya", "Aarav", "Zoya"}) visitors.add(name);
        System.out.println("Unique visitors: " + visitors.size());                       // 2
        System.out.println("Visited? " + (visitors.contains("Aarav") ? "yes" : "no"));   // yes
    }
}

Go

package main

import "fmt"

func yesNo(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

func main() {
	// HashMap: the built-in map (key => value)
	marks := map[string]int{}
	marks["Raju"] = 12
	marks["Mira"] = 9
	marks["Raju"] = 15                  // same key: value replaced
	fmt.Println("Raju:", marks["Raju"]) // 15
	_, has := marks["Mira"]
	fmt.Println("Has Mira?", yesNo(has))
	delete(marks, "Mira") // delete
	_, has = marks["Mira"]
	fmt.Println("Has Mira?", yesNo(has))

	// HashSet: a map whose values are just true, so each key appears once
	visitors := map[string]bool{}
	for _, name := range []string{"Zoya", "Aarav", "Zoya"} {
		visitors[name] = true
	}
	fmt.Println("Unique visitors:", len(visitors))    // 2
	fmt.Println("Visited?", yesNo(visitors["Aarav"])) // yes
}

Time: O(1) average · Extra space: O(n). Adding, finding and deleting a key each take about one hashed step, and the structure stores the n entries.

Watch out for

  • Using a list and searching it for membership (O(n)) when a set would answer in one step.
  • In PHP, using $map[$k] without checking isset first: a missing key raises a warning.
  • Expecting objects as keys to work like strings. In a JavaScript Map two equal-looking objects are different keys.

Quick check

  1. What does a HashSet store?
    • Key and value pairs
    • Unique values only
    • Sorted numbers
  2. You set the same key twice in a HashMap. What happens?
    • Two entries exist
    • An error occurs
    • The latest value replaces the old one
  3. Which is faster for "have I seen this value?" on a million items?
    • HashSet
    • Looping through a list
    • They are the same