π§ What is Time Complexity?
Think of time complexity like asking:
"How many steps will my program take as the input gets bigger?"
Imagine you're:
- π§Έ Putting LEGO blocks one by one (
O(n)) - π² Checking only the first one (
O(1)) - π Flipping every page of a big book to find a word (
O(n)) - π΅οΈ Searching in a sorted drawer by cutting it in half every time (
O(log n))
π Big O Notation β Like Candy Boxes!
Letβs say you have n candies:
β O(1) β "I take 1 candy, no matter how many I have"
def get_first(candies):
return candies[0]
No matter if you have 10 or 10,000 candies β you just grab the first one. π―
β O(n) β "I check every candy"
def find_sour_candy(candies):
for candy in candies:
if candy == 'sour':
return True
If there are 5 candies, you may look 5 times. If there are 100? You might look 100 times!
β O(nΒ²) β "I compare every candy with every other candy"
def find_duplicates(candies):
for i in candies:
for j in candies:
if i == j and i != j:
return True
Imagine youβre checking every candy against every other candy β it gets super slow when the pile grows! π¬π¬π¬
β O(log n) β "I cut the candy box in half each time!"
def binary_search(candies, target):
left, right = 0, len(candies) - 1
while left <= right:
mid = (left + right) // 2
if candies[mid] == target:
return True
elif candies[mid] < target:
left = mid + 1
else:
right = mid - 1
Smart search! Cut your pile in half every time until you find the candy π
β O(n log n) β "Sort candies smartly!"
Merge sort, quicksort β faster than checking every pair like O(nΒ²), but slower than O(n)
π Analogy Recap:
| Big O | Like this... |
|---|---|
| O(1) | Grab the first candy π¬ |
| O(n) | Taste every candy one by one π |
| O(nΒ²) | Compare every candy with every other candy π΅ |
| O(log n) | Smart guess by cutting box in half each time πͺ |
| O(n log n) | Smart sorting like organizing Lego blocks fast π§± |
π§© Exercise 1: Candy Basket π¬
You have a basket of n candies. You want to find if there's any red candy.
def has_red(candies):
for candy in candies:
if candy == "red":
return True
β What's the time complexity?
β Answer:
O(n)β you may need to check all the candies!
π§© Exercise 2: Toy Shelf π§Έ
You have a list of 10 toys. You always play with the first one.
def play_with_toy(toys):
return toys[0]
β Time complexity?
β Answer:
O(1)β always 1 step, no matter how many toys!
π§© Exercise 3: Checking Every Friend's Name π§π¦
You want to say hi to every friend at the party.
def say_hi(friends):
for friend in friends:
print("Hi", friend)
β Time complexity?
β Answer:
O(n)β say "Hi" once per friend!
π§© Exercise 4: Double Trouble π
You want to check every pair of kids to see if theyβre best friends.
def check_best_friends(kids):
for kid1 in kids:
for kid2 in kids:
if kid1 != kid2:
print(f"{kid1} and {kid2} might be besties!")
β Time complexity?
β Answer:
O(nΒ²)β for each kid, check with every other kid.
π§© Exercise 5: Magic Box π¦
You have a sorted list of stickers. You want to find "Unicorn" using binary search.
def find_unicorn(stickers):
left, right = 0, len(stickers) - 1
while left <= right:
mid = (left + right) // 2
if stickers[mid] == "Unicorn":
return True
elif stickers[mid] < "Unicorn":
left = mid + 1
else:
right = mid - 1
β Time complexity?
β Answer:
O(log n)β cut the box in half each time!
β¨ Challenge Yourself:
Try to guess the Big O for these:
- Reversing a list of
nitems - Adding an item to a dictionary
- Looping twice one after the other (not nested)
- Creating all possible pairs in a list
- Looping inside a loop inside a loop (3 levels!)
Big-O Time Complexities Cheat Sheet
| Category | Operation / Pattern | Time Complexity |
|---|---|---|
| Arrays | Traversal, updates | O(n) |
| Merge Sort | O(n log n) | |
| Quick Sort (average) | O(n log n) | |
| Quick Sort (worst case) | O(nΒ²) | |
| Binary Search | O(log n) | |
| Two-pointer / Sliding Window | O(n) | |
| Prefix Sum construction | O(n) | |
| Strings | Reverse / Palindrome check | O(n) |
| Hashmap-based Anagram check | O(n) | |
| Sorting-based Anagram check | O(n log n) | |
| Linked List | Reverse (iterative / recursive) | O(n) |
| Detect Cycle (Floydβs) | O(n) | |
| Merge Two Sorted Lists | O(n) | |
| Find Middle Node | O(n) | |
| Stack / Queue | Push / Pop / Enqueue / Dequeue | O(1) |
| Valid Parentheses | O(n) | |
| Next Greater Element (Monotonic Stack) | O(n) | |
| Hashing | Insert / Search / Delete (average) | O(1) |
| Count Frequencies | O(n) | |
| Subarray with Sum / No Repeats | O(n) | |
| Recursion / Backtracking | Subsets / Permutations | O(2^n * n) |
| Trees (Binary) | Traversals (Inorder / Pre / Post / Level) | O(n) |
| Height, LCA, Validate BST | O(n) | |
| Heaps | Insert / Delete (Min / Max heap) | O(log n) |
| Build heap (heapify array) | O(n) | |
| Dynamic Programming | 0/1 Knapsack | O(n * W) |
| Fibonacci (memoized) | O(n) | |
| Longest Common Subsequence (LCS) | O(n * m) | |
| Graphs | DFS / BFS traversal | O(V + E) |
| Detect Cycle (undirected) | O(V + E) | |
| Topological Sort | O(V + E) |
Top comments (0)