Data Structures & AlgorithmsModerateGATE CS · TCS NQT
Problem: An undirected forest (a graph with no cycles) has 9 vertices and 6 edges. How many connected components does it have?
- A. 4
- B. 2
- C. 3
- D. 5
Correct answer: C. 3
A forest with n vertices and c components has n − c edges, so 9 − 6 = 3 components. Using the edge count directly as components is the classic slip.
More Coding Interview Problems questions
- Problem: A rooted tree (root 1) has parent pointers: 2→1, 3→1, 4→2, 5→2, 6→4, 7→6, 8→3, 9→8. How many nodes lie on the path between node 7…
- Problem: For the complete binary tree with 10 nodes stored in heap order (node i has children 2i and 2i+1, root is node 1), what is the…
- Problem: Using the parent array par[i] for nodes 0–9 with par = [−1, 0, 0, 1, 1, 3, 3, 5, 6, 8], what is the 3rd ancestor of node 9 (the…
- Problem: Count the indices i of the string "abacaba" for which the suffix s[i:] is a palindrome.
- Problem: Deleting exactly one character from "aabca" produces some strings. How many distinct strings can result?
- Problem: Find the maximum sum of a strictly increasing subsequence of [1, 101, 2, 3, 100, 4, 5].