📖 Scenario: Imagine you are organizing a social network where people can be friends with multiple others, and friendships can be mutual or one-way. Trees cannot represent this well because they only allow one parent per node and no cycles. Graphs help model these complex connections.
🎯 Goal: You will create a simple graph using an adjacency list to represent friendships between people. You will see why trees cannot model such relationships by comparing the structure.
📋 What You'll Learn
Create an adjacency list object called friendGraph with exact entries for people and their friends
Create a variable called person set to the string 'Alice'
Write a function called getFriends that takes a person's name and returns their friends from friendGraph
Print the friends of person using the getFriends function
💡 Why This Matters
🌍 Real World
Social networks, recommendation systems, and transportation maps use graphs to model complex connections.
💼 Career
Understanding graphs is essential for software engineers working on networked applications, data analysis, and algorithms.
Progress0 / 4 steps
1
Create the graph data structure
Create an adjacency list object called friendGraph with these exact entries: 'Alice': ['Bob', 'Charlie'], 'Bob': ['Alice', 'David'], 'Charlie': ['Alice'], 'David': ['Bob']
DSA Javascript
Hint
Use an object where keys are names and values are arrays of friends.
2
Set the person to check friends for
Create a variable called person and set it to the string 'Alice'
DSA Javascript
Hint
Use const person = 'Alice';
3
Write a function to get friends
Write a function called getFriends that takes a parameter name and returns friendGraph[name]
DSA Javascript
Hint
Define a function that returns the array of friends for the given name from friendGraph.
4
Print the friends of the person
Print the friends of person by calling getFriends(person) using console.log
DSA Javascript
Hint
Use console.log(getFriends(person)); to print the friends.
Practice
(1/5)
1. Why do we need graphs when we already have trees in data structures?
easy
A. Because graphs can represent connections between nodes in any direction, including cycles.
B. Because trees are faster to search than graphs.
C. Because trees can only store numbers, not other data types.
D. Because graphs use less memory than trees.
Solution
Step 1: Understand tree limitations
Trees are hierarchical and cannot represent cycles or multiple parent connections.
Step 2: Understand graph capabilities
Graphs allow nodes to connect in any way, including cycles and multiple parents.
Final Answer:
Because graphs can represent connections between nodes in any direction, including cycles. -> Option A
Quick Check:
Graphs model cycles and complex connections = C [OK]
Hint: Graphs allow cycles; trees do not [OK]
Common Mistakes:
Thinking trees can have cycles
Confusing memory use between trees and graphs
Assuming trees only store numbers
2. Which of the following is the correct way to represent an undirected graph using adjacency lists in JavaScript?
easy
A. const graph = [ [1, 2], [2, 3], [3, 1] ];
B. const graph = { 1: [2, 3], 2: [1], 3: [1] };
C. const graph = { 1: 2, 2: 3, 3: 1 };
D. const graph = [[1, 2], [2, 3], [3, 1]];
Solution
Step 1: Understand adjacency list format
An adjacency list uses an object with keys as nodes and values as arrays of connected nodes.
Step 2: Check each option
const graph = { 1: [2, 3], 2: [1], 3: [1] }; correctly uses an object with arrays for neighbors; others use incorrect formats.
Graph has nodes A->B, B->C,D, C->A forming a cycle A->B->C->A.
Step 2: Trace hasCycle function
Function detects cycles using recursion and stack tracking; it returns true when cycle found.
Final Answer:
true -> Option D
Quick Check:
Cycle detected in graph = true [OK]
Hint: Cycle detection returns true if back edge found [OK]
Common Mistakes:
Ignoring the cycle from C back to A
Assuming no cycles in directed graphs
Confusing visited and stack usage
4. The following code attempts to check if a graph has cycles but has a bug. What is the bug?
const graph = {
1: [2],
2: [3],
3: [1]
};
function detectCycle(node, visited) {
if (visited[node]) return true;
visited[node] = true;
for (const neighbor of graph[node]) {
if (detectCycle(neighbor, visited)) return true;
}
return false;
}
console.log(detectCycle(1, {}));
medium
A. The graph object keys should be strings, not numbers.
B. The visited object is not initialized properly.
C. The function does not track recursion stack to detect back edges.
D. The function should return false immediately after visiting a node.
Solution
Step 1: Understand cycle detection logic
Detecting cycles in directed graphs requires tracking recursion stack to find back edges.
Step 2: Identify missing recursion stack tracking
Code only uses visited set, so it cannot distinguish between visited nodes in current path and others.
Final Answer:
The function does not track recursion stack to detect back edges. -> Option C
Quick Check:
Missing recursion stack tracking = bug [OK]
Hint: Track recursion stack to detect cycles in directed graphs [OK]
Common Mistakes:
Assuming visited alone detects cycles
Confusing graph keys types
Returning false too early
5. You want to model a social network where users can follow each other, including mutual follows and cycles. Which data structure best models this, and why can't a tree be used here?
hard
A. Use a graph because it supports cycles and multiple connections; trees cannot model cycles or multiple parents.
B. Use a tree because it is simpler and supports mutual connections.
C. Use an array because it can store all users linearly.
D. Use a linked list because it supports cycles naturally.
Solution
Step 1: Understand social network connections
Users can follow each other mutually, creating cycles and multiple parent connections.
Step 2: Compare data structures
Trees are hierarchical and cannot represent cycles or multiple parents; graphs can model these complex relationships.
Final Answer:
Use a graph because it supports cycles and multiple connections; trees cannot model cycles or multiple parents. -> Option A
Quick Check:
Social network needs graph for cycles = A [OK]
Hint: Social networks need graphs for cycles and mutual links [OK]
Common Mistakes:
Choosing trees for mutual connections
Using arrays or lists for complex relations
Ignoring cycles in social networks
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.