AlgoTales · Roadmap

Directed/undirected graphs

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

Where you will meet this in real life

In an undirected graph, a link works both ways, like a handshake. In a directed graph, a link has a direction, like following someone on Instagram: you may follow them without them following you back. Choosing correctly decides whether your data means what you think.

Practical use cases

  • Web app: Followers versus friends. A social app has "Follow" (one way) and "Friends" (both ways). Followers are a directed graph, and friendships are an undirected one. If the app stored follows as friendships, users would see people they never accepted as friends, so the choice shows up directly in the feature.
  • Web app: Task dependencies in a project board. A project tool lets you mark "Design must finish before Build". That arrow has a direction, since Build does not need to finish before Design. A directed graph lets the tool order tasks and warn when two tasks wait on each other forever. Teams spot circular waiting before it blocks a release.
  • System: Web links and one-way streets. Links between web pages are directed, since page A linking to B does not mean B links to A. Road maps with one-way streets are directed too, while a footpath you can walk either way is undirected. Getting the direction wrong sends drivers the wrong way down a street.

The story: Handshakes and One-Way Lanes

During the school annual day, Mira and Kabir were both given jobs. Mira had to record who shook hands with whom at the gate. Kabir had to record who followed whom on the school's photo page.

Mira drew a line between two kids whenever they shook hands. One line was enough: if Aarav shook hands with Zoya, then Zoya shook hands with Aarav. The line works both ways. No arrow needed.

Kabir hit a problem. Zoya followed the cricket star, but the cricket star did not follow Zoya! One line was not enough to tell the story. So he drew an arrow from Zoya to the star. The arrow said who points at whom, and which way. Now the picture told the truth.

The teacher, Mrs. Sharma, listened to both of them very carefully and then clapped: "Mira drew an undirected graph, Kabir drew a directed graph. Always ask: does this relationship go both ways, or only one?"

How to spot this problem, and where you need it

You are unsure whether a relationship in your data goes both ways or only one way, and the wrong choice gives wrong results, like showing someone as a friend who never accepted.

Signs you need it

  • The relationship can be unequal: A follows B, A blocks B, A depends on B, A links to B.
  • Requests such as "who follows me?" differ from "who do I follow?", which needs two separate lists.
  • Storing a link needs one row per direction or just one row, and you are not sure which.

Where to use it in a project

  • Social features: follow versus friend, block lists and mutual connections.
  • Task dependencies, course prerequisites and one-way routes in navigation.

The solution

Ask "if A is linked to B, is B automatically linked to A?" If yes, use an undirected graph and store the link once for both dots. If not, use a directed graph and store it only from A to B. Then "who follows me" means looking at lines coming in, and "who do I follow" means lines going out.

Payoff: Before: followers shown as friends and wrong counts. After: separate follower and following lists that always match the real relationship.

Explain it like I am 8

A handshake needs two hands, so it goes both ways. Calling someone on the phone is different: you may call them but they may not call you back. Lines without arrows are handshakes. Lines with arrows are phone calls.

How it works, step by step

  1. Ask the question: if A is linked to B, is B automatically linked to A? Yes means undirected, no means directed.
  2. Undirected: when you add edge A-B, store it for both A and B.
  3. Directed: store A → B only for A. B does not get anything unless you add B → A separately.
  4. Walking a directed graph means only following arrows forward. Walking an undirected graph allows both directions.

The code in four languages

PHP

<?php
// Undirected: one friendship is stored in BOTH people's lists.
function addUndirected(array &$g, string $a, string $b): void {
    $g[$a][] = $b;
    $g[$b][] = $a;
}
// Directed: the arrow is stored only for the giver.
function addDirected(array &$g, string $from, string $to): void {
    $g[$from][] = $to;
    if (!isset($g[$to])) $g[$to] = [];   // make sure the target exists
}

$friends = [];
addUndirected($friends, 'Zoya', 'Aarav');
$follows = [];
addDirected($follows, 'Zoya', 'Star');

echo 'Aarav friends with Zoya? ' . (in_array('Zoya', $friends['Aarav']) ? 'yes' : 'no') . "\n";
echo 'Star follows Zoya? ' . (in_array('Zoya', $follows['Star']) ? 'yes' : 'no') . "\n";
echo 'Zoya follows Star? ' . (in_array('Star', $follows['Zoya']) ? 'yes' : 'no') . "\n";

JavaScript

// Undirected: one friendship is stored in BOTH people's lists.
function addUndirected(g, a, b) {
  (g[a] = g[a] || []).push(b);
  (g[b] = g[b] || []).push(a);
}
// Directed: the arrow is stored only for the giver.
function addDirected(g, from, to) {
  (g[from] = g[from] || []).push(to);
  if (!g[to]) g[to] = [];               // make sure the target exists
}

const friends = {};
addUndirected(friends, 'Zoya', 'Aarav');
const follows = {};
addDirected(follows, 'Zoya', 'Star');

console.log('Aarav friends with Zoya? ' + (friends['Aarav'].includes('Zoya') ? 'yes' : 'no'));
console.log('Star follows Zoya? ' + (follows['Star'].includes('Zoya') ? 'yes' : 'no'));
console.log('Zoya follows Star? ' + (follows['Zoya'].includes('Star') ? 'yes' : 'no'));

Java

import java.util.*;

public class Main {
    // Undirected: one friendship is stored in BOTH people's lists.
    static void addUndirected(Map<String, List<String>> g, String a, String b) {
        g.computeIfAbsent(a, k -> new ArrayList<>()).add(b);
        g.computeIfAbsent(b, k -> new ArrayList<>()).add(a);
    }

    // Directed: the arrow is stored only for the giver.
    static void addDirected(Map<String, List<String>> g, String from, String to) {
        g.computeIfAbsent(from, k -> new ArrayList<>()).add(to);
        g.computeIfAbsent(to, k -> new ArrayList<>());   // make sure the target exists
    }

    static String yesNo(boolean b) { return b ? "yes" : "no"; }

    public static void main(String[] args) {
        Map<String, List<String>> friends = new HashMap<>();
        addUndirected(friends, "Zoya", "Aarav");
        Map<String, List<String>> follows = new HashMap<>();
        addDirected(follows, "Zoya", "Star");

        System.out.println("Aarav friends with Zoya? " + yesNo(friends.get("Aarav").contains("Zoya")));
        System.out.println("Star follows Zoya? " + yesNo(follows.get("Star").contains("Zoya")));
        System.out.println("Zoya follows Star? " + yesNo(follows.get("Zoya").contains("Star")));
    }
}

Go

package main

import "fmt"

type Graph map[string][]string

// addUndirected stores one friendship in BOTH people's lists.
func addUndirected(g Graph, a, b string) {
	g[a] = append(g[a], b)
	g[b] = append(g[b], a)
}

// addDirected stores the arrow only for the giver.
func addDirected(g Graph, from, to string) {
	g[from] = append(g[from], to)
	if _, ok := g[to]; !ok {
		g[to] = []string{} // make sure the target exists
	}
}

func contains(list []string, x string) bool {
	for _, s := range list {
		if s == x {
			return true
		}
	}
	return false
}

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

func main() {
	friends := Graph{}
	addUndirected(friends, "Zoya", "Aarav")
	follows := Graph{}
	addDirected(follows, "Zoya", "Star")

	fmt.Println("Aarav friends with Zoya?", yesNo(contains(friends["Aarav"], "Zoya")))
	fmt.Println("Star follows Zoya?", yesNo(contains(follows["Star"], "Zoya")))
	fmt.Println("Zoya follows Star?", yesNo(contains(follows["Zoya"], "Star")))
}

Time: O(1) to add an edge · Extra space: O(V + E). An undirected edge is stored twice (once per end), a directed edge once.

Watch out for

  • Adding only one side of an undirected edge. Then walking from the other side finds nothing.
  • Adding both sides for a directed graph, which quietly turns it into an undirected one.
  • Forgetting that in a directed graph "reachable from A" and "A is reachable from" are different questions.

Quick check

  1. Which relationship is naturally directed?
    • Two kids shaking hands
    • Who follows whom on a photo page
    • Two cities joined by a two-way road
  2. You add the undirected edge A-B to an adjacency list. What do you store?
    • B in A's list only
    • Nothing yet
    • A in B's list and B in A's list
  3. In a directed graph there is an arrow A → B only. Can you walk from B to A?
    • No, not along that arrow
    • Yes, always
    • Only on Sundays