Mastering HashSet in C# for Coding Interviews
seonglinchua

seonglinchua @seonglinchua

About: Self-taught C# dev with 10+ yrs experience. I simplify backend, automation & cloud. On a mission to help devs grow through real-world stories & modern practices.

Joined:
Sep 9, 2019

Mastering HashSet in C# for Coding Interviews

Publish Date: May 10
0 1

🧠 HashSet in C# — A Must-Know Tool for Uniqueness and Fast Lookups

HashSet<T> is one of the most versatile and commonly used data structures in coding interviews. It allows constant-time lookup and guarantees unique elements only.


✅ When to Use HashSet

Use Case Why Use HashSet
Check for duplicates Fast Contains() check
Track seen items O(1) add/lookup
Unique collections Prevents duplicates automatically
Set operations (union/intersect) Built-in set logic

✍️ Declaring and Using HashSet

var seen = new HashSet<int>();

seen.Add(5);        // true
seen.Add(5);        // false (duplicate)

bool exists = seen.Contains(5); // true
seen.Remove(5);     // removes 5
Enter fullscreen mode Exit fullscreen mode

🔁 Looping Through HashSet

foreach (int num in seen)
{
    Console.WriteLine(num);
}
Enter fullscreen mode Exit fullscreen mode

🧪 Interview Example 1: Detect Duplicates

public bool ContainsDuplicate(int[] nums)
{
    var set = new HashSet<int>();
    foreach (int num in nums)
    {
        if (!set.Add(num)) return true;
    }
    return false;
}
Enter fullscreen mode Exit fullscreen mode

🧪 Interview Example 2: Longest Substring Without Repeating Characters

public int LengthOfLongestSubstring(string s)
{
    var set = new HashSet<char>();
    int left = 0, maxLen = 0;

    for (int right = 0; right < s.Length; right++)
    {
        while (set.Contains(s[right]))
        {
            set.Remove(s[left]);
            left++;
        }

        set.Add(s[right]);
        maxLen = Math.Max(maxLen, right - left + 1);
    }

    return maxLen;
}
Enter fullscreen mode Exit fullscreen mode

⚙️ Set Operations

var a = new HashSet<int>() { 1, 2, 3 };
var b = new HashSet<int>() { 2, 3, 4 };

a.IntersectWith(b);  // a = {2, 3}
a.UnionWith(b);      // a = {1, 2, 3, 4}
a.ExceptWith(b);     // a = {1}
Enter fullscreen mode Exit fullscreen mode

📌 Summary

Feature Syntax Example
Declare new HashSet<int>()
Add set.Add(value)
Check Exists set.Contains(value)
Remove set.Remove(value)
Set Ops UnionWith(), IntersectWith()

Next up: Dictionary — perfect for counting, mapping, and solving problems like Two Sum and Group Anagrams.

Comments 1 total

  • Ghost Engineer
    Ghost EngineerMay 31, 2025

    try this if you get stuck during the interview. its an AI co-pilot that solves the questions for you so you can focus on the more important part of the interview, the communication part. its also a really good study tool: ghostengineer.com

Add comment