Hash Sets

DSA · Hashing

Theory

A hash set stores unique values with no associated data, using the same hashing idea as a hash table. Adding, removing and checking membership are O(1) on average. Sets also support union, intersection and difference, which makes them ideal for comparing groups.

Why we use it

Sets remove duplicates automatically and answer "have I seen this before?" instantly.

When to use it

Use sets for de-duplication, visited-node tracking in graphs, membership checks and comparing collections.

How it works

  1. For each item
  2. Item in set? Yes: Duplicate found / skip. No: Add item to set.
  3. Set holds unique items

Syntax

s = set()
s.add(x); s.remove(x); x in s     O(1) avg
a | b  union    a & b  intersection
a - b  difference   a ^ b  symmetric difference

Example

visits = ["home", "sql", "home", "dsa", "sql", "blog"]
unique_pages = set(visits)
print("Unique pages:", sorted(unique_pages))

asha = {"SQL", "Python", "Power BI"}
ravi = {"SQL", "Snowflake", "Python"}
print("Both know:", sorted(asha & ravi))
print("Only Asha:", sorted(asha - ravi))
print("All skills:", sorted(asha | ravi))

def has_duplicate(nums):
    seen = set()
    for n in nums:
        if n in seen:
            return True
        seen.add(n)
    return False
print("Duplicate in [1,2,3,1]:", has_duplicate([1, 2, 3, 1]))

Key points

DSA topics

Introduction to DSA

Arrays and Searching

Sorting Algorithms

Linked Lists

Stacks and Queues

Hashing

Trees

Heaps

Graphs

Algorithm Techniques

Classic Algorithms

Dynamic Programming

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Data Structures & Algorithms

The complete DSA roadmap: theory, why and when to use every structure and algorithm, Big O complexity, and Python code you can run right here in the browser.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice DSA Online 251 problems across 13 patterns, with hidden tests and step-by-step optimal solutions. Start practising →
Section {{ sec.num }}

{{ sec.label }}

DSA  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ current.why }}

When to use it

{{ current.when }}

Flowchart — how {{ current.name }} works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Step-by-step visualisation
{{ cell.v }}
{{ cell.i }} {{ cell.tag }}
Step {{ vizStepLabel }}: {{ vizNote }}
■ comparing ■ swapping / moving ■ done / found ■ out of range
Complexity & Pseudocode
{{ current.syntax }}
Example Code
{{ current.example }}
▶ Try It Live — runs real Python 3 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic