C# || How To Find The Largest Component Size By Common Factor Using C#

Print Friendly, PDF & Email

The following is a module with functions which demonstrates how to find the largest component size by common factor using C#.


1. Largest Component Size – Problem Statement

You are given an integer array of unique positive integers nums. Consider the following graph:

  • There are nums.length nodes, labeled nums[0] to nums[nums.length – 1],
  • There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1.

Return the size of the largest connected component in the graph.

Example 1:

Example 1


Input: nums = [4,6,15,35]
Output: 4

Example 2:

Example 2


Input: nums = [20,50,9,63]
Output: 2

Example 3:

Example 3


Input: nums = [2,3,6,7,4,12,21,39]
Output: 8


2. Largest Component Size – Solution

The following is a solution which demonstrates how to find the largest component size by common factor.

The following solution uses a union find set to group connections together.

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:


4
2
8

Was this article helpful?
👍 YesNo

Leave a Reply