DEV Community

seonglinchua
seonglinchua

Posted on

Mastering HashSet in C# for Coding Interviews

๐Ÿง  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.

Top comments (1)

Collapse
 
ghost_engineer_2883a1ca0a profile image
Ghost Engineer

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