Back to Data Structures

Sets

Unique collections with fast membership testing

What Makes Sets Special

Sets store unique elements with O(1) membership testing. Unlike arrays, adding a duplicate has no effect. Sets shine for deduplication, quick lookups, and mathematical set operations.

Use Sets For:

  • • Removing duplicates from a list
  • • Fast membership checking (is X in the set?)
  • • Finding common elements between groups
  • • Tracking unique visitors/items

Set Operations:

  • Union: All elements from both sets
  • Intersection: Elements in both sets
  • Difference: Elements in A but not B
  • Symmetric: Elements in one but not both

Venn Diagram Visualization

Set ASet B12345678

Set A

1
2
3
4
5

Set B

4
5
6
7
8

Complexity Analysis

OperationAverageNotes
AddO(1)Duplicates ignored
Has (membership)O(1)Much faster than array includes
DeleteO(1)No shifting needed
Union/IntersectionO(n)Must iterate through sets