📖 Scenario: Imagine you are creating a simple map of cities connected by roads. Each city is a point (vertex), and each road is a connection (edge) between cities. Some roads have directions (one-way), and some have distances (weights).
🎯 Goal: You will build a basic graph using TypeScript objects to represent cities and roads. You will mark if roads are one-way or two-way and add distances to roads.
📋 What You'll Learn
Create a graph object with cities as keys and arrays of connected cities as values
Add a configuration variable to mark if the graph is directed or undirected
Add weights (distances) to the edges
Print the graph connections with directions and weights
💡 Why This Matters
🌍 Real World
Graphs are used to model maps, social networks, computer networks, and many other connections in real life.
💼 Career
Understanding graph basics is important for software developers working on navigation apps, recommendation systems, and network analysis.
Progress0 / 4 steps
1
Create the graph with cities and roads
Create a variable called graph as an object with these exact entries: 'A': ['B', 'C'], 'B': ['C'], 'C': ['A']
DSA Typescript
Hint
Use an object where keys are city names and values are arrays of connected cities.
2
Add a variable to mark if the graph is directed
Create a boolean variable called isDirected and set it to true
DSA Typescript
Hint
This variable will help us know if roads have directions or not.
3
Add weights (distances) to the edges
Create a variable called weightedGraph as an object where each city key maps to an array of objects with node and weight properties. Use these exact entries: 'A': [{ node: 'B', weight: 5 }, { node: 'C', weight: 10 }], 'B': [{ node: 'C', weight: 3 }], 'C': [{ node: 'A', weight: 1 }]
DSA Typescript
Hint
Use an object with arrays of objects to store connected nodes and their distances.
4
Print the graph connections with directions and weights
Use a for loop with variables city and edges to iterate over Object.entries(weightedGraph). Inside the loop, use another for loop with variables edge to iterate over edges. Print each connection in this exact format: "City A -> City B (Distance: 5)" using console.log
DSA Typescript
Hint
Use nested loops to print each road with its distance.
Practice
(1/5)
1. In a graph, what do we call the points or nodes where edges meet?
easy
A. Edges
B. Weights
C. Vertices
D. Paths
Solution
Step 1: Understand graph components
A graph consists of points called nodes and connections called edges.
Step 2: Identify the term for nodes
The points or nodes where edges meet are called vertices.
Final Answer:
Vertices -> Option C
Quick Check:
Nodes = Vertices [OK]
Hint: Nodes in graphs are called vertices [OK]
Common Mistakes:
Confusing edges with vertices
Thinking weights are nodes
Mixing paths with nodes
2. Which of the following is the correct way to represent a weighted edge from vertex 1 to vertex 2 with weight 5 in TypeScript?
easy
A. const edge = { 1: 2, 5 };
B. const edge = [1, 2, 5];
C. const edge = (1, 2, 5);
D. const edge = { from: 1, to: 2, weight: 5 };
Solution
Step 1: Understand object syntax in TypeScript
Objects use key-value pairs with curly braces and colons.
Step 2: Check each option's syntax
const edge = { from: 1, to: 2, weight: 5 }; correctly uses keys 'from', 'to', and 'weight' with values. const edge = [1, 2, 5]; is an array, valid but less descriptive. const edge = (1, 2, 5); uses parentheses, invalid for object. const edge = { 1: 2, 5 }; has invalid syntax.
Final Answer:
const edge = { from: 1, to: 2, weight: 5 }; -> Option D
Quick Check:
Object with keys and values = const edge = { from: 1, to: 2, weight: 5 }; [OK]
Hint: Use curly braces and key:value pairs for objects [OK]
Common Mistakes:
Using parentheses instead of braces
Incorrect object key syntax
Confusing arrays with objects
3. What will be the output of the following TypeScript code that creates a directed weighted graph and prints its edges?
type Edge = { from: number; to: number; weight: number };
const graph: Edge[] = [
{ from: 1, to: 2, weight: 3 },
{ from: 2, to: 3, weight: 4 },
{ from: 3, to: 1, weight: 5 }
];
for (const edge of graph) {
console.log(`${edge.from} -> ${edge.to} (weight: ${edge.weight})`);
}
The graph array has edges: 1->2 with weight 3, 2->3 with weight 4, 3->1 with weight 5.
Step 2: Trace the for loop output
The loop prints each edge in the format 'from -> to (weight: weight)'. So output matches 1 -> 2 (weight: 3)
2 -> 3 (weight: 4)
3 -> 1 (weight: 5) exactly.
Which code snippet correctly calculates the total weight of edges connected to vertex 2?
hard
A. const total = graph[2].map(edge => edge.weight).length;
B. const total = graph[2].reduce((sum, edge) => sum + edge.weight, 0);
C. const total = graph[2].filter(edge => edge.weight > 0);
D. const total = graph.reduce((sum, edges) => sum + edges.weight, 0);
Solution
Step 1: Understand adjacency list structure
graph[2] is an array of edges connected to vertex 2, each with a weight property.
Step 2: Calculate total weight
Use reduce to sum all edge weights in graph[2]. const total = graph[2].reduce((sum, edge) => sum + edge.weight, 0); correctly sums weights. const total = graph[2].map(edge => edge.weight).length; counts edges, not sum. const total = graph[2].filter(edge => edge.weight > 0); filters edges, no sum. const total = graph.reduce((sum, edges) => sum + edges.weight, 0); tries to reduce graph object, invalid.
Final Answer:
const total = graph[2].reduce((sum, edge) => sum + edge.weight, 0); -> Option B
Quick Check:
Sum weights with reduce = const total = graph[2].reduce((sum, edge) => sum + edge.weight, 0); [OK]
Hint: Use reduce to sum weights in adjacency list [OK]
Common Mistakes:
Using map length instead of sum
Filtering without summing
Reducing wrong data structure
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.