![]() |
VOOZH | about |
Given an array A[] of size N, for each index i in the range [0, N) the value A[i] denotes the size of the connected component of node i. The task is to find the edges for the possible graph else print -1.
Note: There may be more than 1 possible answers for each array. Print any one of them.
Examples:
Input: N = 5, A[] = {2, 1, 1, 2, 1}
Output: {{0, 3}}
Explanation: The size of Connected Components of nodes (0, 3) is 2, every other node is singular.Input: N = 4, A[] = {2, 2, 2, 2}
Output: {{0, 1}, {2, 3}}
Explanation: Other possible variations are - {{0, 2}, {1, 3}}, {{0, 3}, {1, 2}}Input: N=2, A[] = {1, 1}
Output: Graph is already connected.
Explanation: Since, each connected component size is 1, no edge is needed to connect any pair of nodes.
Approach: The idea is to observe that all the same component sizes can be connected with each other using total nodes equal to the size of the array value. So, store all the nodes with the same index value into a map. The values of nodes can be stored with a map structure map<int, vector<int>>. Check for each size of connected component that the corresponding total nodes are a multiple of the size. If for any connected component the above condition fails then there will be no valid graph. Return -1 immediately. Otherwise for all multiple stores the vertices and connect them adjacently. Store all edges in an array and output the result. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
[{0, 3}]Time Complexity: O(N*log(N))
Auxiliary Space: O(N)