Menu
Coddy logo textTech

Math - Union of HashSets

Part of the Logic & Flow section of Coddy's C# journey — lesson 62 of 66.

The Union operation combines two sets to create a new set that contains all elements from both sets, without duplicates.

Create two HashSets:

HashSet<int> set1 = new HashSet<int>() { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5 };

Use the Union method to combine the sets:

HashSet<int> unionSet = new HashSet<int>(set1);
unionSet.UnionWith(set2);

After executing the above code, the unionSet contains:

[1, 2, 3, 4, 5]

Notice that the element 3 appears only once in the result, as HashSet doesn't allow duplicates.

challenge icon

Challenge

Easy

Create a method named UnionSets that takes two HashSets of integers as parameters and returns a new HashSet containing the union of both sets.

The input reading and output printing are already handled for you — focus on implementing the UnionSets method body.

Cheat sheet

The Union operation combines two sets to create a new set that contains all elements from both sets, without duplicates.

Create two HashSets:

HashSet<int> set1 = new HashSet<int>() { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5 };

Use the Union method to combine the sets:

HashSet<int> unionSet = new HashSet<int>(set1);
unionSet.UnionWith(set2);

The result contains all unique elements from both sets. Duplicates are automatically removed.

Try it yourself

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

class Program
{
    public static HashSet<int> UnionSets(HashSet<int> set1, HashSet<int> set2)
    {
        // Write your code here
        return null;
    }
    
    static void Main(string[] args)
    {
        // Read first line to check format for first set
        string line1 = Console.ReadLine();
        HashSet<int> set1 = new HashSet<int>();
        
        // Check if first set is in JSON array format
        if (line1 != null && line1.StartsWith("[") && line1.EndsWith("]"))
        {
            try
            {
                // Extract content between square brackets
                string arrayContent = line1.Substring(1, line1.Length - 2);
                
                // Try to parse the JSON array content
                string[] values = Regex.Split(arrayContent, @",\s*");
                foreach (string value in values)
                {
                    // Remove any quotes if present
                    string cleanValue = value.Trim();
                    if (cleanValue.StartsWith("\"") && cleanValue.EndsWith("\""))
                    {
                        cleanValue = cleanValue.Substring(1, cleanValue.Length - 2);
                    }
                    
                    // Parse as integer and add to set
                    if (int.TryParse(cleanValue, out int num))
                    {
                        set1.Add(num);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing first set: {ex.Message}");
                return;
            }
        }
        else
        {
            // Process traditional space-separated input for first set
            string[] input1 = line1.Split(' ');
            foreach (string num in input1)
            {
                if (int.TryParse(num, out int parsedNum))
                {
                    set1.Add(parsedNum);
                }
            }
        }
        
        // Read second line to check format for second set
        string line2 = Console.ReadLine();
        HashSet<int> set2 = new HashSet<int>();
        
        // Check if second set is in JSON array format
        if (line2 != null && line2.StartsWith("[") && line2.EndsWith("]"))
        {
            try
            {
                // Extract content between square brackets
                string arrayContent = line2.Substring(1, line2.Length - 2);
                
                // Try to parse the JSON array content
                string[] values = Regex.Split(arrayContent, @",\s*");
                foreach (string value in values)
                {
                    // Remove any quotes if present
                    string cleanValue = value.Trim();
                    if (cleanValue.StartsWith("\"") && cleanValue.EndsWith("\""))
                    {
                        cleanValue = cleanValue.Substring(1, cleanValue.Length - 2);
                    }
                    
                    // Parse as integer and add to set
                    if (int.TryParse(cleanValue, out int num))
                    {
                        set2.Add(num);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing second set: {ex.Message}");
                return;
            }
        }
        else
        {
            // Process traditional space-separated input for second set
            string[] input2 = line2.Split(' ');
            foreach (string num in input2)
            {
                if (int.TryParse(num, out int parsedNum))
                {
                    set2.Add(parsedNum);
                }
            }
        }
        
        // Get union and print result
        HashSet<int> unionSet = UnionSets(set1, set2);
        Console.WriteLine(string.Join(" ", unionSet.OrderBy(x => x)));
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow