Sitemap

Member-only story

Good Graph

3 min readFeb 18, 2024

--

Problem Description:

Given a directed graph of N nodes where each node points to exactly one of the N nodes (can point to itself). Ishu, the coder, is bored and he has discovered a problem out of it to keep himself busy. The problem is as follows:

A node is ‘good’ if it satisfies one of the following:

1. It is the special node (marked as node 1)
2. It is pointing to the special node (node 1)
3. It is pointing to a good node.

Ishu is going to change the pointers of some nodes to make them all ‘good’. You must find the minimum number of pointers to change to make all the nodes good (Thus, a Good Graph).

NOTE: Resultant Graph should hold the property that all nodes are good and each node must point to exactly one node.

Problem Constraints:

1 <= N <= 105

Example:

Input:

[1, 2, 1, 2]

Output: 1

Explanation: The pointer of node 2 is made to point to node 1.

Understanding:

As the question says a graph is a good graph when all the nodes of the graph are good. The node will be a good node when it follows three conditions, It is the special node (marked as node 1), It is pointing to the special node (node…

--

--

Malhotraashish
Malhotraashish

Written by Malhotraashish

Curious written, willing to learn more, willing to read more, willing to expand more