Lesson 20 of 30
Trees keep things neat and tidy. Graphs let connections point anywhere, even back to where you started — which turns out to be more honest about how real relationships work.
9 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
This topic is about judgment and practical tradeoffs more than a single right answer — a mock interview is the better way to test yourself on it.
Be interviewed on this →Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
Think about your friends on a social network. Each of your friends has their own friends. Follow that chain far enough and it can loop back around — a friend of a friend of a friend turns out to be you. That's a graph.
A tree, which you've already met, is neat and tidy: everyone has exactly one parent, nothing loops back, and there's one clear starting point at the top. A graph throws that tidiness out. Connections can point anywhere. Two people can be linked directly and also share ten mutual friends, so there are many possible paths between them, not one single path.
That messiness isn't a flaw. It's what makes graphs useful. Real relationships aren't tidy hierarchies. Roads connect cities in a tangle, not a tree. Web pages link to each other in loops. Your friends' friends really can include you. A graph is the data structure that's honest about that.
If trees already felt like a lot, hearing "now forget the neat rules" might feel discouraging. It shouldn't. A graph isn't a harder tree — it's a more relaxed one. Fewer rules to remember, not more.
// Each person points to the friends they know directly.
// Notice "sam" appears under "alex" AND "alex" appears under "sam" —
// this friendship goes both ways.
const friendships = {
alex: ["sam", "jordan"],
sam: ["alex", "jordan"],
jordan: ["alex", "sam", "casey"],
casey: ["jordan"],
};
console.log(friendships.alex); // ["sam", "jordan"]
// This is the loop a tree could never have: alex is friends with jordan,
// and jordan is friends with alex. Following connections "forward"
// can lead right back where you started.
console.log(friendships.jordan.includes("alex")); // true
You've already worked with trees, which are graphs with the loops removed and a strict one-parent rule added on top. A graph is the more general shape underneath. The plain JavaScript object used above to represent friendships is the same kind of object you already know from the JavaScript track — graphs don't need a special new syntax to exist.