DEV Community

Cover image for ๐Ÿ’ก TIME COMPLEXITY PRIMER โ€“ Understand Big O Like a Kid With Candies ๐Ÿฌ
Ankush Singh Gandhi
Ankush Singh Gandhi

Posted on

๐Ÿ’ก TIME COMPLEXITY PRIMER โ€“ Understand Big O Like a Kid With Candies ๐Ÿฌ

๐Ÿง  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]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

โ“ 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]
Enter fullscreen mode Exit fullscreen mode

โ“ 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)
Enter fullscreen mode Exit fullscreen mode

โ“ 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!")
Enter fullscreen mode Exit fullscreen mode

โ“ 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
Enter fullscreen mode Exit fullscreen mode

โ“ Time complexity?

โœ… Answer: O(log n) โ€” cut the box in half each time!


โœจ Challenge Yourself:

Try to guess the Big O for these:

  1. Reversing a list of n items
  2. Adding an item to a dictionary
  3. Looping twice one after the other (not nested)
  4. Creating all possible pairs in a list
  5. 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)