📖 Scenario: Imagine you are organizing a group of friends who want to share rides to different places. Some friends can drive others, and some can be passengers. You want to represent these relationships to understand who can reach whom. Trees are like family trees with one clear path, but sometimes friends have multiple connections that trees cannot show well. Graphs help us model these complex connections.
🎯 Goal: You will build a simple graph using an adjacency list in TypeScript to represent friends and their ride-sharing connections. This will show why trees are not enough when multiple connections exist.
📋 What You'll Learn
Create a graph using an adjacency list with exact friend names and connections
Add a variable to count the total number of friends
Write a function to add a new friend connection
Print the adjacency list to show all connections
💡 Why This Matters
🌍 Real World
Graphs help model complex relationships like social networks, road maps, and ride-sharing connections where multiple links exist between entities.
💼 Career
Understanding graphs is essential for software roles involving network analysis, recommendation systems, and any scenario with interconnected data.
Progress0 / 4 steps
1
Create the initial graph with friends and their connections
Create a constant called rideGraph as an object with these exact keys and values: 'Alice': ['Bob', 'Charlie'], 'Bob': ['Alice', 'David'], 'Charlie': ['Alice'], 'David': ['Bob']
DSA Typescript
Hint
Use an object where each friend name is a key and the value is an array of friends they can ride with.
2
Add a variable to count total friends
Create a constant called totalFriends and set it to the number of keys in rideGraph using Object.keys(rideGraph).length
DSA Typescript
Hint
Use Object.keys() to get all friend names and then get the length.
3
Add a function to add a new friend connection
Create a function called addConnection that takes two parameters friend1 and friend2 both strings. Inside the function, add friend2 to rideGraph[friend1] array and friend1 to rideGraph[friend2] array. Assume both friends already exist in rideGraph.
DSA Typescript
Hint
Use the push method to add connections to each friend's array.
4
Print the graph to show all friend connections
Use console.log(rideGraph) to print the entire adjacency list showing all friends and their connections.
DSA Typescript
Hint
Use console.log(rideGraph) to see the full graph structure.
Practice
(1/5)
1. Why do we need graphs when we already have trees in data structures?
easy
A. Because trees can only store numbers, not other data types.
B. Because trees are faster to traverse than graphs.
C. Because graphs are simpler and have no edges.
D. Because graphs can represent connections between nodes in any pattern, including cycles.
Solution
Step 1: Understand tree limitations
Trees are hierarchical and cannot have cycles or multiple parents for a node.
Step 2: Understand graph capabilities
Graphs allow any connections, including cycles and multiple edges between nodes.
Final Answer:
Because graphs can represent connections between nodes in any pattern, including cycles. -> Option D
Quick Check:
Graphs model cycles, trees cannot [OK]
Hint: Graphs allow cycles; trees do not [OK]
Common Mistakes:
Thinking trees can have cycles
Confusing data types with structure
Assuming graphs are simpler than trees
2. Which of the following is the correct way to declare an adjacency list for a graph in TypeScript?
easy
A. const graph: number = [];
B. const graph: number[][] = [];
C. const graph: string = {};
D. const graph: boolean[] = {};
Solution
Step 1: Identify adjacency list type
An adjacency list is an array of arrays, where each inner array holds connected node indices.
Step 2: Match TypeScript syntax
TypeScript syntax for adjacency list is number[][] for array of number arrays.
Final Answer:
const graph: number[][] = []; -> Option B
Quick Check:
Adjacency list = number[][] [OK]
Hint: Adjacency list is array of arrays [OK]
Common Mistakes:
Using single number type for adjacency list
Using object {} instead of array []
Wrong type annotations
3. Consider the following TypeScript code representing a graph with cycles:
A. It returns false immediately if node is visited, missing cycles.
B. It never marks nodes as visited.
C. It uses wrong data types for visited and stack arrays.
D. It does not check neighbors of the node.
Solution
Step 1: Analyze early return on visited node
Returning false immediately when node is visited skips cycle detection on back edges.
Step 2: Understand correct cycle detection logic
Should only return false if node visited and not in recursion stack; else return true if in stack.
Final Answer:
It returns false immediately if node is visited, missing cycles. -> Option A
Quick Check:
Early return on visited node causes missed cycles [OK]
Hint: Do not return false immediately on visited node [OK]
Common Mistakes:
Returning false too early
Confusing visited and recursion stack
Ignoring recursion stack check
5. You want to model a social network where users can follow each other in any pattern, including mutual follows and cycles. Which data structure best models this, and why can't a tree be used?
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 cycles naturally.
C. Use a linked list because it models one-way connections well.
D. Use an array because it stores all users efficiently.
Solution
Step 1: Identify social network connection patterns
Users can follow each other in any pattern, including cycles and mutual connections.
Step 2: Compare data structures
Trees cannot represent cycles or multiple parents; graphs can represent any connection pattern.
Final Answer:
Use a graph because it supports cycles and multiple connections; trees cannot model cycles or multiple parents. -> Option A
Quick Check:
Graphs model social networks; trees cannot [OK]
Hint: Social networks need graphs for cycles and mutual links [OK]
Common Mistakes:
Choosing tree for cyclic connections
Confusing linked list with graph
Ignoring cycles in social networks
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.