Menu
Coddy logo textTech

Math - Intersection of HashSet

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

The intersection of two sets contains only the elements that appear in both sets.

Create two HashSets:

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

To find the intersection, use the IntersectWith method:

set1.IntersectWith(set2);

After executing this code, set1 will contain:

{ 3, 4, 5 }

The IntersectWith method modifies the set it's called on, keeping only elements that exist in both sets.

To create a new set with the intersection without modifying the original sets, you can:

HashSet<int> intersection = new HashSet<int>(set1);
intersection.IntersectWith(set2);
challenge icon

Challenge

Medium

Create a method named FindCommonElements that takes two arguments:

  • A HashSet of integers (set1)
  • A HashSet of integers (set2)

The method should return a new HashSet containing only the elements that appear in both sets (the intersection).

Cheat sheet

The intersection of two sets contains only elements that appear in both sets.

Use IntersectWith method to find intersection:

HashSet<int> set1 = new HashSet<int>() { 1, 2, 3, 4, 5 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5, 6, 7 };
set1.IntersectWith(set2); // set1 now contains { 3, 4, 5 }

The IntersectWith method modifies the original set. To preserve the original set, create a copy first:

HashSet<int> intersection = new HashSet<int>(set1);
intersection.IntersectWith(set2);

Try it yourself

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

class Program {
    public static HashSet<int> FindCommonElements(HashSet<int> set1, HashSet<int> set2) {
        // Write your code here
        return null;
    }
    
    static void Main(string[] args) {
        // Read first line 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 s in input1) {
                if (int.TryParse(s, out int num)) {
                    set1.Add(num);
                }
            }
        }
        
        // Read second line 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 s in input2) {
                if (int.TryParse(s, out int num)) {
                    set2.Add(num);
                }
            }
        }
        
        // Find common elements
        HashSet<int> common = FindCommonElements(set1, set2);
        
        // Print result (sorted)
        Console.WriteLine(string.Join(" ", common.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