DEV Community

Sreekar Reddy
Sreekar Reddy

Posted on β€’ Originally published at sreekarreddy.com

🎯 Sets Explained Like You're 5

Collections with no duplicates

Day 135 of 149

πŸ‘‰ Full deep-dive with code examples


The Guest List Analogy

You're making a party guest list:

  • Add "Alice" β†’ Alice is on the list
  • Add "Bob" β†’ Bob is on the list
  • Add "Alice" again β†’ Nothing happens! She's already there

Sets work like guest lists!

Every item appears exactly once. Duplicates are automatically ignored.


The Problem They Solve

Sometimes you need unique items:

  • "What unique words are in this document?"
  • "Who has visited this page?"
  • "Which tags are used in this article?"

With arrays, you'd have to check for duplicates yourself. Sets handle it automatically!


What Sets Can Do

Membership check (fast!):

  • "Is Alice on the list?" β†’ Yes/No instantly

Add items:

  • Adds if not there
  • Ignores if already present

Remove items:

  • Takes the item out

Set operations:

  • Union: Combine two sets
  • Intersection: What's in BOTH sets?
  • Difference: What's in one but not the other?

A Simple Example

Set A: {apple, banana, cherry}
Set B: {banana, date, elderberry}

Union: {apple, banana, cherry, date, elderberry}
Intersection: {banana}
Difference (A-B): {apple, cherry}
Enter fullscreen mode Exit fullscreen mode

When To Use Sets

Use sets when:

  • You need unique items only
  • You need fast "is this in here?" checks
  • You don't care about order
  • You want to find common or unique items between groups

Sets vs Arrays

Arrays Sets
Can have duplicates Only unique items
Ordered Usually unordered
Find item: slow (scan) Find item: instant

In One Sentence

Sets store unique items only, making it fast to check membership and find what's common or different between groups.


πŸ”— Enjoying these? Follow for daily ELI5 explanations!

Making complex tech concepts simple, one day at a time.

Top comments (0)