• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Mastering HashSet in C# for Coding Interviews

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
? 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 CaseWhy Use HashSet
Check for duplicatesFast Contains() check
Track seen itemsO(1) add/lookup
Unique collectionsPrevents 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
? Looping Through HashSet


foreach (int num in seen)
{
Console.WriteLine(num);
}
? 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;
}
? 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
))
{
set.Remove(s
);
left++;
}

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

return maxLen;
}
⚙ 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}
? Summary

FeatureSyntax Example
Declarenew HashSet<int>()
Addset.Add(value)
Check Existsset.Contains(value)
Removeset.Remove(value)
Set Ops UnionWith(), IntersectWith()

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


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу