- RECURSION
- Call Stack
- Iterative Approach
- Memoization
- Head Tail
- Mental Checklist
- Dfs Traversal
- Bfs Traversal
- DATA STRUCTURES
- Time Complexity
- Lists
-
Sets
- Hash Tables
- Stacks
- Queues
- Linked Lists
- Trees
- Binary Search Trees
- Tries
- Graphs
- COMPARISION BASED
- Bubble Sort
- Selection Sort
- Merge Sort
- DIVIDE CONQUER
- Binary Search
- Quicksort
- Karatsuba Multiplication
- GRAPH TRAVERSAL
- Flood Fill
- Depth First Search
- Breadth First Search
- Dijkstra's Algorithm
- DECISION MAKING
- Minimax
- GREEDY
- Coin Change
- Fractional Knapsack
ALGORITHMS PAGES -
LEVEL 3
PVM / Python / Data Structures / Sets
1. Inserting Sets
In terms of time compexity, the only difference between lists and sets is at insertion. Reading O(1), Searching O(n), Deleting O(n), Inserting O(1) A set stores unique, unordered elements (it rejects duplicates). Insertion is (on average) O(1) thanks to hashing. As analogy, think of a guest list where each name can appear only once. Adding a new name is instant, trying to add an existing name changes nothing. Inserting mutates the input set. There is no need for duplicate checks. Python sets already handle duplicates in O(1).
py
# Inserting into a set O(1)
fruits = {'apples', 'bananas', 'oranges'}
# Custom insert function
def add_item(items, value):
steps = 0
# Duplicate check
# for item in items:
# steps += 1
# if item == value:
# return -1
# Insert (set chooses the storage location, order is arbitrary)
items.add(value)
steps += 1
return steps
steps = add_item(fruits, 'kiwi')
print(fruits, steps)
"""
{'bananas', 'apples', 'kiwi', 'oranges'} 1
"""