Graphs and Hashing

Back

Loading concept...

πŸ—ΊοΈ Graphs & Hashing: The City Map & Magic Locker Adventure

Imagine you’re the mayor of a tiny town. You need two superpowers: a map to show how everything connects, and magic lockers that instantly find anything you put inside. That’s Graphs and Hashing!


πŸ™οΈ Part 1: Graph Fundamentals β€” Your Town Map

What is a Graph?

Think of a graph like a connect-the-dots puzzle. You have:

  • Dots (we call them nodes or vertices)
  • Lines connecting them (we call them edges)

Simple Example:

Your house -------- School
     |                |
     |                |
   Park ----------- Store

That’s a graph! Four places (nodes) connected by roads (edges).

Real Life:

  • πŸ—ΊοΈ Google Maps showing roads between cities = Graph
  • πŸ‘₯ Facebook showing who’s friends with who = Graph
  • ✈️ Flight routes between airports = Graph

πŸ“š Graph Terminology β€” Learning the Words

Like learning a new game, you need to know the special words:

Term What It Means Example
Node/Vertex A dot (a thing) Your house, a city, a person
Edge A line (a connection) A road, a friendship, a wire
Neighbor Nodes connected by an edge Houses next door to each other
Degree How many edges touch a node A popular person has high degree
Path A walk from one node to another Walking from home β†’ park β†’ school
Cycle A path that ends where it started Walking in a complete circle

Picture it:

graph TD A["🏠 Home"] --> B["πŸ“š School"] A --> C["🌳 Park"] B --> D["πŸͺ Store"] C --> D

Home has degree 2 (two roads going out). The path Home β†’ Park β†’ Store β†’ School β†’ Home is a cycle!


πŸ—‚οΈ Graph Representations β€” How Computers Remember Maps

A computer can’t draw pictures. It needs to store the map in numbers. There are two main ways:

1️⃣ Adjacency List (The Neighbor List)

Like a phone book! Each place lists its neighbors.

Home:    [School, Park]
School:  [Home, Store]
Park:    [Home, Store]
Store:   [School, Park]

βœ… Good for: Most graphs (saves memory) πŸ“¦ Space: O(Nodes + Edges)

2️⃣ Adjacency Matrix (The Big Chart)

A table where βœ“ means β€œconnected” and βœ— means β€œnot connected.”

        Home  School  Park  Store
Home      βœ—      βœ“      βœ“     βœ—
School    βœ“      βœ—      βœ—     βœ“
Park      βœ“      βœ—      βœ—     βœ“
Store     βœ—      βœ“      βœ“     βœ—

βœ… Good for: Quickly checking β€œAre A and B connected?” πŸ“¦ Space: O(Nodes Γ— Nodes)


➑️ Directed vs Undirected Graphs

Undirected Graph (Two-Way Streets)

If you can walk from Home to School, you can walk back. The connection goes both ways.

graph LR A["Home"] --- B["School"]

Example: Friendships on Facebook (if you’re my friend, I’m your friend)

Directed Graph (One-Way Streets)

Some roads only go one direction! We use arrows to show which way.

graph LR A["You"] --> B["Celebrity"]

Example: Following on Twitter (you can follow a celebrity, but they might not follow you back!)


βš–οΈ Weighted Graphs β€” Roads Have Distances

What if some roads are longer than others? We add weights (numbers) to edges!

graph LR A["Home"] -->|5 km| B["School"] A -->|2 km| C["Park"] B -->|8 km| D["Airport"] C -->|3 km| D

Why it matters:

  • Home β†’ School β†’ Airport = 5 + 8 = 13 km
  • Home β†’ Park β†’ Airport = 2 + 3 = 5 km ← Shorter!

Real Life: GPS finding the fastest route considers traffic (weights)!


πŸ” Part 2: Hash Tables β€” The Magic Locker Room

What is a Hash Table?

Imagine a locker room with 10 lockers. You want to store your backpack instantly without checking every locker.

The Magic: A special spell (hash function) tells you EXACTLY which locker to use based on your name!

"Alice" β†’ Spell β†’ Locker 3
"Bob"   β†’ Spell β†’ Locker 7

Now finding Alice’s stuff? Instant! Just use the spell again: β€œAlice” β†’ Locker 3. Open it!

Real Life:

  • πŸ“– Dictionaries (word β†’ definition)
  • πŸ“§ Email contacts (name β†’ email address)
  • πŸ”‘ Passwords (username β†’ encrypted password)

πŸͺ„ Hash Functions β€” The Magic Spell

A hash function takes ANY input and gives back a number (locker number).

Simple Example β€” Adding Letter Positions:

"CAT" β†’ C(3) + A(1) + T(20) = 24
If we have 10 lockers: 24 % 10 = Locker 4

Good Hash Function Rules:

Rule Why?
Fast Computing the locker should be instant
Consistent Same input ALWAYS gives same output
Spread out Different inputs should go to different lockers

Bad hash function: Always returns 1 (everyone fights for locker 1!)

Good hash function: Spreads items evenly across all lockers.


πŸ’₯ Hash Collisions β€” Two People, One Locker!

Uh oh! What if the spell sends TWO people to the SAME locker?

"Alice" β†’ Locker 3
"Amy"   β†’ Locker 3  ← COLLISION!

Solution 1: Chaining (Locker has a List)

Put a linked list in each locker. Both Alice and Amy share locker 3.

Locker 3: [Alice's bag] β†’ [Amy's bag]

Solution 2: Open Addressing (Find Next Empty)

If locker 3 is taken, try locker 4, then 5…

"Alice" β†’ Locker 3 βœ“
"Amy"   β†’ Locker 3 βœ— full β†’ Locker 4 βœ“

Solution 3: Double Hashing (Second Spell)

Use a SECOND hash function to calculate how many lockers to skip.

"Amy" β†’ First spell says 3 (full!)
     β†’ Second spell says "skip 2"
     β†’ Try locker 5 βœ“

πŸ“¦ Sets and Maps β€” Special Collections

Set: A Bag of Unique Items

A Set is like a bag where each toy appears only ONCE.

myToys = {car, doll, ball, car}  ← car appears twice!
After Set magic: {car, doll, ball}  ← only one car!

Uses:

  • Removing duplicates from a list
  • Checking if something exists (membership test)
  • Finding common items between two groups

Map (Dictionary): Key β†’ Value Pairs

A Map is like a phonebook: every name (key) has one phone number (value).

phoneBook = {
  "Mom": "555-1234",
  "Dad": "555-5678",
  "Pizza": "555-0000"
}

Lookup: β€œWhat’s Mom’s number?” β†’ Instant answer: β€œ555-1234”

Note: Sets use hash tables (just keys, no values). Maps use hash tables too (keys + values)!


🀝 Union-Find β€” The Friend Groups Tracker

The Problem

You have 100 students. They keep making friends. You need to answer:

β€œAre Alex and Zoe in the same friend group?”

Checking every friendship would be slow!

The Solution: Union-Find (Disjoint Set)

Think of each friend group having a team captain.

Two Operations:

  1. Find(person): Who’s your team captain?
  2. Union(person1, person2): Merge two teams!

Example:

Start: Everyone is their own captain
  [A] [B] [C] [D] [E]

Union(A, B): A becomes captain of B
  [A-B] [C] [D] [E]

Union(C, D): C becomes captain of D
  [A-B] [C-D] [E]

Union(B, D): Merge teams! A becomes everyone's captain
  [A-B-C-D] [E]

Find(D) = A (captain)
Find(E) = E (still alone)

The Superpower: Path Compression

When finding the captain, make everyone point directly to the captain!

graph TD subgraph Before A1["A"] --> B1["B"] --> C1["C"] --> D1["D"] end subgraph After Find D A2["A"] --> D2["D"] B2["B"] --> D2 C2["C"] --> D2 end

Now future lookups are super fast!

Real Life Uses:

  • 🌐 Detecting if two computers are on the same network
  • πŸ–ΌοΈ Image processing (grouping similar pixels)
  • 🧩 Solving maze connections

🎯 Quick Summary

Concept One-Line Explanation
Graph Dots connected by lines
Vertex/Node A dot (thing)
Edge A line (connection)
Directed One-way arrows
Undirected Two-way streets
Weighted Edges have numbers (distance, cost)
Adjacency List Each node lists its neighbors
Adjacency Matrix A table showing all connections
Hash Table Magic lockers with instant lookup
Hash Function The spell that picks the locker
Collision Two items want the same locker
Chaining Fix collision with lists in lockers
Open Addressing Fix collision by finding next empty
Set Bag of unique items only
Map Key-value phonebook
Union-Find Track which things are in the same group

πŸš€ You Did It!

You now understand:

  • βœ… How to represent connections (Graphs)
  • βœ… Two ways computers store graphs (List vs Matrix)
  • βœ… One-way vs two-way connections
  • βœ… Roads with distances (Weighted graphs)
  • βœ… Instant lookup magic (Hash tables)
  • βœ… What happens when two items collide
  • βœ… Sets (unique items) and Maps (key-value)
  • βœ… Finding who’s in the same group (Union-Find)

You’re ready to build maps, create fast lookups, and track connections like a pro! πŸŽ‰

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.