Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Data Structures
Data Structureseasy

What is a Set and when would you use it?

Tags
#set#deduplication#membership
Back to categoryPractice quiz

Answer

A Set stores unique values (no duplicates). Use it for fast membership checks and deduplication (e.g., keep unique user IDs).

const ids = new Set<number>();
ids.add(42);
console.log(ids.has(42)); // true

Advanced answer

Deep dive

A Set is an abstract data type built around one idea: store unique values and answer membership queries quickly (have I seen X?). In many languages it is backed by a hash table, which gives average O(1) add/has/delete, but can degrade to O(n) in worst cases (poor hashing, adversarial input, very high load factor).

Use a Set when:

  • You need deduplication (unique IDs, unique tags, unique emails).
  • You need fast membership checks (feature flags, allowed roles, cache keys).
  • You track visited nodes/states in traversals (BFS/DFS/Dijkstra).

Examples

const users = ['a', 'b', 'a', 'c']
const unique = [...new Set(users)] // ['a', 'b', 'c']

const allowed = new Set(['admin', 'editor'])
const canEdit = allowed.has(role)

Language notes

  • Java: HashSet uses hashCode() + equals(). If you store custom objects, implement both consistently.
  • JS/TS: Set compares primitives by value, but objects by identity (two objects with same fields are still different).

Common pitfalls

  • Expecting Set to deduplicate objects by fields (it will not).

Related questions

Microservices
At-least-once delivery: how do you avoid duplicate side effects in a consumer?
#idempotency#deduplication#messaging
MongoDB
`$push` vs `$addToSet` — what’s the difference?
#mongodb#arrays#update
MongoDB
In MongoDB updates, what does `$set` do?
#mongodb#update
  • Mutating an object that affects hashing/equality after inserting into a hash-based set.
  • Using Set when you actually need key -> value (use Map).
  • #set
    Java
    HashSet vs TreeSet — what’s the difference?
    #set#hashset#treeset