HashSet for unique elements in C Sharp (C#) - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
We want to understand how fast a HashSet can add and check unique items.
How does the time to add or check items grow as we add more elements?
Analyze the time complexity of the following code snippet.
HashSet<int> uniqueNumbers = new HashSet<int>();
int[] numbers = {1, 2, 3, 2, 4, 5, 3};
foreach (int num in numbers)
{
uniqueNumbers.Add(num);
}
This code adds numbers to a HashSet to keep only unique values.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each number to the HashSet.
- How many times: Once for each number in the input array.
Each new number is checked and added quickly, so the time grows roughly in a straight line with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 add/check operations |
| 100 | About 100 add/check operations |
| 1000 | About 1000 add/check operations |
Pattern observation: The work grows evenly as the input grows.
Time Complexity: O(n)
This means the time to add all items grows directly with the number of items.
[X] Wrong: "Adding to a HashSet takes longer and longer as it gets bigger."
[OK] Correct: HashSet uses a smart way to find spots quickly, so adding stays fast even with many items.
Knowing how HashSet works helps you explain why it's great for finding unique items quickly in real projects.
"What if we used a List instead of a HashSet to keep unique items? How would the time complexity change?"
Practice
HashSet<T> in C#?Solution
Step 1: Understand HashSet behavior
A HashSet automatically ignores duplicate entries and stores only unique elements.Step 2: Compare with other collections
Unlike lists or dictionaries, HashSet does not allow duplicates and does not maintain order.Final Answer:
To store unique elements without duplicates -> Option CQuick Check:
HashSet = Unique elements [OK]
- Thinking HashSet keeps elements sorted
- Assuming HashSet allows duplicates
- Confusing HashSet with Dictionary
HashSet<int> with values 1, 2, and 3?Solution
Step 1: Check HashSet initialization syntax
HashSet can be initialized with collection initializer syntax using curly braces after the constructor.Step 2: Validate each option
var set = new HashSet<int> {1, 2, 3}; uses correct syntax: new HashSet<int> {1, 2, 3}; Options A, B, and C have invalid syntax.Final Answer:
var set = new HashSet<int> {1, 2, 3}; -> Option BQuick Check:
Use curly braces after constructor for initialization [OK]
- Using parentheses with multiple values directly
- Trying to declare array instead of HashSet
- Incorrect assignment syntax
var set = new HashSet<string>();
set.Add("apple");
set.Add("banana");
set.Add("apple");
Console.WriteLine(set.Count);Solution
Step 1: Add elements to HashSet
"apple" is added first, then "banana", then "apple" again.Step 2: Understand duplicate handling
The second "apple" is ignored because HashSet stores unique elements only.Final Answer:
2 -> Option DQuick Check:
Duplicates ignored, count = 2 [OK]
- Counting duplicates as separate elements
- Assuming HashSet allows duplicates
- Confusing Count with number of Add calls
HashSet<int>:HashSet<int> numbers = new HashSet<int>(); numbers.Add(1); numbers.Add(2); numbers.Add(1); Console.WriteLine(numbers[0]);
Solution
Step 1: Review HashSet usage
HashSet stores unique elements but does not support accessing elements by index.Step 2: Identify invalid operation
Using numbers[0] causes a compile-time error because HashSet has no indexer.Final Answer:
HashSet does not support indexing with [] -> Option AQuick Check:
No index access on HashSet [OK]
- Trying to access elements by index
- Thinking Add returns a value
- Assuming duplicates cause errors
List<int> nums = new List<int> {1, 2, 2, 3, 4, 4, 4, 5};Which code snippet correctly creates a
HashSet<int> containing only the unique elements from nums?Solution
Step 1: Understand HashSet constructor
HashSet has a constructor that accepts an IEnumerable<T> to initialize with unique elements.Step 2: Analyze each option
var unique = new HashSet<int>(nums); correctly passes the list to the constructor. var unique = new HashSet<int>(); unique.Add(nums); tries to add the whole list as one item (invalid). var unique = new HashSet<int>(); foreach(var n in nums) unique = n; assigns int to HashSet variable (invalid). var unique = new HashSet<int>(); unique.AddRange(nums); uses AddRange which HashSet does not have.Final Answer:
var unique = new HashSet<int>(nums); -> Option AQuick Check:
Use constructor with collection for unique set [OK]
- Using Add to add whole list at once
- Trying to assign int to HashSet variable
- Using AddRange which HashSet lacks
