Algorithms with C# · Lesson 4

Sets and uniqueness

Track whether a value has already appeared.

How it works

A HashSet represents membership rather than an ordered list of occurrences. Add returns true only when it inserts a value that was not already present according to the comparer. This makes duplicate detection direct: a false result identifies a repeated key without scanning every earlier input. The set contains unique keys, while the separate list preserves duplicate events in encounter order.

Decide whether repeated duplicates should be reported once or once per occurrence; those are different requirements. Hash-based collections rely on a consistent equality and hash contract, so avoid mutating fields that determine a key’s identity while it is stored.

Add a third A and observe that it creates another duplicate event. Change the reporting structure to a second set if the requirement is one report per duplicated identifier.

A working example

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

var seen = new HashSet<string>(StringComparer.Ordinal);
var duplicates = new List<string>();
foreach (var value in new[] { "A", "B", "A", "C", "B" }) if (!seen.Add(value)) duplicates.Add(value);
Console.WriteLine(string.Join(",", duplicates));

Expected output

A,B
Try this
Add reports whether this occurrence introduced a new member.