Using Sets

Not Started

A set stores unique elements with O(1) add, remove, and membership checks. No duplicates, no ordering guarantees. Use it when you only care whether something exists.

When to Use

Fast membership tests: Is this vowel? Is this position blocked? O(1) beats scanning a list.
Removing duplicates: Convert a list to a set and back. Only unique elements remain.
Tracking visited states: BFS/DFS often store visited nodes in a set to avoid cycles.
Storing obstacle positions: Queen's Attack uses a set of (row, col) tuples for instant collision checks.

Create a Set

seen = set()                # empty set
vowels = set("aeiouAEIOU")  # from iterable
nums = {1, 2, 3}            # literal syntax
unordered_set<int> seen;                  // empty set
unordered_set<char> vowels("aeiouAEIOU",
                           "aeiouAEIOU" + 10);  // from range
unordered_set<int> nums = {1, 2, 3};      // initializer list
var seen = new HashSet<int>();              // empty set
var vowels = new HashSet<char>("aeiouAEIOU"); // from IEnumerable
var nums = new HashSet<int> { 1, 2, 3 };    // collection initializer
Set<Integer> seen = new HashSet<>();       // empty set
Set<Character> vowels = new HashSet<>(
    Arrays.asList('a','e','i','o','u'));      // from collection

Add an Element

seen.add(5)  # adds 5; no effect if already present
seen.insert(5);  // adds 5; no effect if already present
seen.Add(5);  // returns true if added, false if duplicate
seen.add(5);  // returns true if added, false if duplicate

Check Membership

if 5 in seen:      # O(1) lookup
    print("found")
if (seen.count(5))   // returns 1 if present, 0 otherwise
    cout << "found";
if (seen.Contains(5))  // returns bool
    Console.WriteLine("found");
if (seen.contains(5))  // returns bool
    System.out.println("found");

Remove an Element

seen.discard(5)  # removes 5; no error if missing
seen.remove(5)   # removes 5; raises KeyError if missing
seen.erase(5);  // removes 5; no error if missing
seen.Remove(5);  // returns true if removed, false if not found
seen.remove(5);  // returns true if removed, false if not found

Loop Through a Set

for item in seen:
    print(item)  # order is arbitrary
for (int item : seen)
    cout << item;  // order is arbitrary
foreach (int item in seen)
    Console.WriteLine(item);  // order is arbitrary
for (int item : seen)
    System.out.println(item);  // order is arbitrary

Get Size

len(seen)  # number of elements
seen.size();  // number of elements
seen.Count;  // number of elements (property)
seen.size();  // number of elements