0
0
DSA Typescriptprogramming~10 mins

Graph vs Tree Key Structural Difference in DSA Typescript - Interactive Comparison Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to check if a graph has no cycles, which is a key property of a tree.

DSA Typescript
function isTree(graph: Map<number, number[]>): boolean {
  // A tree has no cycles
  return !hasCycle(graph, [1]);
}
Drag options to blanks, or click blank then click option'
A1
B0
C-1
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Starting cycle check from a non-existent node like 0 or -1.
2fill in blank
medium

Complete the code to count edges in a tree given nodes count n.

DSA Typescript
function countEdgesInTree(n: number): number {
  // A tree with n nodes has [1] edges
  return n - 1;
}
Drag options to blanks, or click blank then click option'
An
Bn + 1
Cn - 1
Dn * 2
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing edges count with nodes count.
3fill in blank
hard

Fix the error in the function that checks if a graph is connected (a tree must be connected).

DSA Typescript
function isConnected(graph: Map<number, number[]>, n: number): boolean {
  const visited = new Set<number>();
  function dfs(node: number) {
    visited.add(node);
    for (const neighbor of graph.get(node) || []) {
      if (!visited.has(neighbor)) {
        dfs([1]);
      }
    }
  }
  dfs(1);
  return visited.size === n;
}
Drag options to blanks, or click blank then click option'
Aneighbor
Bnode
Cgraph
Dvisited
Attempts:
3 left
💡 Hint
Common Mistakes
Calling dfs on the current node again causing infinite recursion.
4fill in blank
hard

Fill both blanks to create a function that checks if a graph is a tree by verifying connectivity and edges count.

DSA Typescript
function isTree(graph: Map<number, number[]>, n: number): boolean {
  const edgesCount = [1];
  const connected = isConnected(graph, n);
  return connected && edgesCount === [2];
}
Drag options to blanks, or click blank then click option'
AcountEdges(graph)
Bn - 1
Cgraph.size
Dn + 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong edges count or ignoring connectivity.
5fill in blank
hard

Fill all three blanks to implement a function that counts edges in an undirected graph represented by adjacency list.

DSA Typescript
function countEdges(graph: Map<number, number[]>): number {
  let count = 0;
  for (const [1] of graph.values()) {
    count += [2];
  }
  return count [3] 2;
}
Drag options to blanks, or click blank then click option'
Aneighbors
Bneighbors.length
C/
D*
Attempts:
3 left
💡 Hint
Common Mistakes
Not dividing by 2, causing double counting.