UBER Coding Question β Solved
Given a set of nodes and a list of connected pairs, determine the order (number of nodes) in each connected component in the graph. For each component, calculate the ceiling of the square root of its order, and return the sum of these values across all connected components.
Example
graph_nodes = 10
graph_from = [1, 1, 2, 3, 7]
graph_to = [2, 3, 4, 5, 8]
There are graph_edges = 5 edges to consider. There are 2 isolated sets with more than one node: {1, 2, 3, 4, 5} and {7, 8}. The ceilings of their square roots are: β5 β 2.236 and ceil(2.236) = 3 β2 β 1.414 and ceil(1.414) = 2
The other three isolated nodes are separate, and the square root of their orders is β1 = 1 respectively. The sum is 3 + 2 + (3 * 1) = 8.
Function Description
Complete the function `connectedSum` in the editor below.
connectedSum has the following parameter(s):
- int graph_nodes: the number of nodes
- int graph_from[graph_edges]: an array of integers that represent one end of an edge
- int graph_to[graph_edges]: an array of integers that represent the other end of an edge
Returns:
- int: an integer that denotes the sum of the values calculated
Constraints
- 2 β€ graph_nodes β€ 10^5
- 1 β€ graph_edges β€ 10^5
- 1 β€ graph_from[i], graph_to[i] β€ n
- graph_from[i] β graph_to[i]
Input Format for Custom Testing
Sample Input 0
STDIN
12 >
4 2
graph_edges = 2 edges
graph_from[] = [1, 1]
graph_to[] = [2, 4]
14
Sample Output 0
graph_nodes = 4 nodes,
3
The values to sum are:
1. Set {1, 2, 4}: ceil(sqrt(3)) = 2
2. Set {3}: ceil(sqrt(1)) = 1
2 + 1 = 3
Asked in:
UBER