easyHash Table 0 views

How Hash Sets Work — API Cheat Sheet

No exercise here — add/contains/remove across Java, C#, Python, and JavaScript/TypeScript, for the "have I seen this before" pattern that shows up everywhere.

This is a reference page, not a graded exercise. A set is a hash map that only stores keys, no values — reach for it whenever a problem is really asking "is this a duplicate" or "have I visited this before," which is a very common pattern.

Java — HashSet<T>

Want to...MethodExample
Createnew HashSet<>()Set<Integer> s = new HashSet<>();
Add.add(v)returns false if it was already present
Check membership.contains(v)s.contains(5)
Remove.remove(v)
Size.size()
Iteratefor-eachfor (int x : s) — no guaranteed order
Build from a collectionnew HashSet<>(list)instant de-duplication

C# — HashSet<T>

Want to...MethodExample
Createnew HashSet<T>()var s = new HashSet<int>();
Add.Add(v)returns false if it was already present
Check membership.Contains(v)s.Contains(5)
Remove.Remove(v)
Size.Countproperty, no parens
Set operations.UnionWith(other), .IntersectWith(other), .ExceptWith(other)mutate s in place

Python — set

Want to...MethodExample
Createset()not {} — that's an empty dict
Create with valuesset literals = {1, 2, 3}
Add.add(v)
Check membershipin5 in s
Remove.remove(v) (raises if missing) / .discard(v) (silent)prefer .discard if you're not sure it's there
Sizelen(s)builtin
Set operationss1 | s2 (union), s1 & s2 (intersection), s1 - s2 (difference)operators, not just methods
Build from a listset(my_list)instant de-duplication

JavaScript / TypeScript — Set<T>

Want to...MethodExample
Createnew Set()const s = new Set<number>();
Add.add(v)
Check membership.has(v)s.has(5)
Remove.delete(v)
Size.sizeproperty, no parens
Iteratefor (const x of s)preserves insertion order
Build from an arraynew Set(arr)instant de-duplication
Back to an array[...s] or Array.from(s)

The gotcha that costs the most time: Python's {} is an empty dict, not an empty set — you must write set() explicitly. And across every language, sets compare objects/structs by reference unless you're using primitives or the language's built-in value types (strings, numbers) — putting two "equal-looking" custom objects into a set won't dedupe them unless you've defined equality/hashing for that type.

Hints

Companies

No companies reported yet.

Discussion

Sign in to join the discussion.

Loading discussion...

Test results

This question doesn't have a code exercise.