0
0
DSA Typescriptprogramming~30 mins

Why Graphs Exist and What Trees Cannot Model in DSA Typescript - See It Work

Choose your learning style9 modes available
Why Graphs Exist and What Trees Cannot Model
📖 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.