Bird
Raised Fist0
DSA Typescriptprogramming

Graph Terminology Vertices Edges Directed Undirected Weighted in DSA Typescript

Choose your learning style10 modes available
Mental Model
A graph is a way to connect points (vertices) with lines (edges) that can have directions and weights.
Analogy: Think of a city map where places are points and roads are lines connecting them. Some roads go one way (directed), some both ways (undirected), and some roads are longer or shorter (weighted).
Vertices: A, B, C, D
Edges:
A -> B (directed)
B ↔ C (undirected)
C -> D (directed, weight 5)

  A -> B
      ↘
       C -> D

Weights shown on edges if any
Dry Run Walkthrough
Input: Graph with vertices A, B, C, D; edges: A->B (directed), B-C (undirected), C->D (directed, weight 5)
Goal: Understand how vertices and edges connect, and how direction and weight affect the graph
Step 1: Identify vertices as points A, B, C, D
Vertices: [A] [B] [C] [D]
Why: Vertices are the main points or nodes in the graph
Step 2: Add directed edge from A to B
A -> B
Vertices: [A] [B] [C] [D]
Why: Directed edge means connection goes only from A to B
Step 3: Add undirected edge between B and C
A -> B ↔ C
Vertices: [A] [B] [C] [D]
Why: Undirected edge means connection goes both ways between B and C
Step 4: Add directed weighted edge from C to D with weight 5
A -> B ↔ C -> D (weight 5)
Vertices: [A] [B] [C] [D]
Why: Weight shows cost or distance on the edge from C to D
Result:
A -> B ↔ C -> D (weight 5)
Vertices: [A] [B] [C] [D]
Annotated Code
DSA Typescript
class Graph {
  vertices: Set<string>;
  edges: Map<string, Array<{to: string; directed: boolean; weight?: number}>>;

  constructor() {
    this.vertices = new Set();
    this.edges = new Map();
  }

  addVertex(v: string) {
    this.vertices.add(v);
    if (!this.edges.has(v)) {
      this.edges.set(v, []);
    }
  }

  addEdge(from: string, to: string, directed: boolean, weight?: number) {
    this.addVertex(from);
    this.addVertex(to);
    this.edges.get(from)!.push({ to, directed, weight });
    if (!directed) {
      this.edges.get(to)!.push({ to: from, directed, weight });
    }
  }

  printGraph() {
    for (const v of this.vertices) {
      const conns = this.edges.get(v)!.map(e => {
        const dir = e.directed ? '->' : '↔';
        const w = e.weight !== undefined ? ` (weight ${e.weight})` : '';
        return `${dir} ${e.to}${w}`;
      });
      console.log(`${v}: ${conns.join(', ')}`);
    }
  }
}

// Driver code
const graph = new Graph();
graph.addEdge('A', 'B', true); // directed A->B
graph.addEdge('B', 'C', false); // undirected B<->C
graph.addEdge('C', 'D', true, 5); // directed C->D with weight 5

graph.printGraph();
this.edges.get(from)!.push({ to, directed, weight });
Add edge from 'from' vertex to 'to' vertex with direction and optional weight
if (!directed) { this.edges.get(to)!.push({ to: from, directed, weight }); }
If edge is undirected, add reverse edge from 'to' to 'from'
for (const v of this.vertices) { const conns = this.edges.get(v)!.map(e => { const dir = e.directed ? '->' : '↔'; const w = e.weight !== undefined ? ` (weight ${e.weight})` : ''; return `${dir} ${e.to}${w}`; }); console.log(`${v}: ${conns.join(', ')}`); }
Print each vertex and its connected edges with direction and weight
OutputSuccess
A: -> B B: ↔ C C: ↔ B, -> D (weight 5) D:
Complexity Analysis
Time: O(V + E) because we add vertices and edges once and print all connections
Space: O(V + E) because we store all vertices and edges in memory
vs Alternative: Compared to adjacency matrix (O(V^2) space), adjacency list used here is more space efficient for sparse graphs
Edge Cases
Adding edge where vertices do not exist yet
Vertices are automatically added before adding edges
DSA Typescript
this.addVertex(from);
Adding undirected edge
Edge is added in both directions to represent two-way connection
DSA Typescript
if (!directed) { this.edges.get(to)!.push({ to: from, directed, weight }); }
Adding weighted edge
Weight is stored and printed alongside the edge
DSA Typescript
const w = e.weight !== undefined ? ` (weight ${e.weight})` : '';
When to Use This Pattern
When a problem involves connecting points with lines that may have directions or costs, think of graph terminology to model vertices, edges, direction, and weights.
Common Mistakes
Mistake: Forgetting to add the reverse edge for undirected edges
Fix: Add the reverse edge explicitly when the edge is undirected
Mistake: Not adding vertices before adding edges causing errors
Fix: Always add vertices first or ensure they exist before adding edges
Summary
Graphs connect points called vertices with lines called edges that can be directed or undirected and may have weights.
Use graph terminology when modeling relationships with direction or cost between items.
Remember edges can go one way (directed) or both ways (undirected), and weights show cost or 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

  1. Step 1: Understand graph components

    A graph consists of points called nodes and connections called edges.
  2. Step 2: Identify the term for nodes

    The points or nodes where edges meet are called vertices.
  3. Final Answer:

    Vertices -> Option C
  4. 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

  1. Step 1: Understand object syntax in TypeScript

    Objects use key-value pairs with curly braces and colons.
  2. 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.
  3. Final Answer:

    const edge = { from: 1, to: 2, weight: 5 }; -> Option D
  4. 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})`);
}
medium
A. 1 -> 2 (weight: 3) 2 -> 3 (weight: 4) 3 -> 1 (weight: 5)
B. 1 -> 2 (weight: 5) 2 -> 3 (weight: 3) 3 -> 1 (weight: 4)
C. 1 -> 3 (weight: 5) 2 -> 1 (weight: 4) 3 -> 2 (weight: 3)
D. Error: Invalid graph definition

Solution

  1. Step 1: Read the graph array

    The graph array has edges: 1->2 with weight 3, 2->3 with weight 4, 3->1 with weight 5.
  2. 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.
  3. Final Answer:

    1 -> 2 (weight: 3) 2 -> 3 (weight: 4) 3 -> 1 (weight: 5) -> Option A
  4. Quick Check:

    Print edges as defined = 1 -> 2 (weight: 3) 2 -> 3 (weight: 4) 3 -> 1 (weight: 5) [OK]
Hint: Match printed edges exactly as in array order [OK]
Common Mistakes:
  • Mixing up weights and vertices
  • Reversing edge directions
  • Assuming syntax error
4. Identify the error in the following TypeScript code that tries to create an undirected weighted graph:
type Edge = { from: number; to: number; weight: number };
const graph: Edge[] = [
  { from: 1, to: 2, weight: 7 },
  { from: 2, to: 1, weight: 7 },
  { from: 2, to: 3, weight: 5 }
];
function addEdge(from: number, to: number, weight: number) {
  graph.push({ from, to, weight });
  graph.push({ from: to, to: from, weight });
}
addEdge(3, 4, 6);
console.log(graph.length);
medium
A. No error; graph length will be 5
B. Error: Duplicate edges cause conflict
C. Error: addEdge function pushes edges incorrectly
D. Error: graph array is immutable

Solution

  1. Step 1: Count initial edges

    Initially, graph has 3 edges: 1->2, 2->1, 2->3.
  2. Step 2: Analyze addEdge function call

    addEdge(3, 4, 6) pushes { from: 3, to: 4, weight: 6 } and { from: 4, to: 3, weight: 6 }, adding 2 more edges for undirected graph.
  3. Step 3: Calculate final length

    3 initial + 2 added = 5. No errors occur; code runs successfully.
  4. Final Answer:

    No error; graph length will be 5 -> Option A
  5. Quick Check:

    3 + 2 = 5 [OK]
Hint: Count edges before and after addEdge call [OK]
Common Mistakes:
  • Assuming duplicate edges cause error
  • Miscounting edges after push
  • Thinking graph is immutable
5. You have a weighted undirected graph represented as an adjacency list in TypeScript:
const graph: Record = {
  1: [{ node: 2, weight: 4 }, { node: 3, weight: 1 }],
  2: [{ node: 1, weight: 4 }, { node: 3, weight: 2 }, { node: 4, weight: 5 }],
  3: [{ node: 1, weight: 1 }, { node: 2, weight: 2 }, { node: 4, weight: 8 }],
  4: [{ node: 2, weight: 5 }, { node: 3, weight: 8 }]
};

// How to find the total weight of edges connected to vertex 2?
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

  1. Step 1: Understand adjacency list structure

    graph[2] is an array of edges connected to vertex 2, each with a weight property.
  2. 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.
  3. Final Answer:

    const total = graph[2].reduce((sum, edge) => sum + edge.weight, 0); -> Option B
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard