Big O Notation Made Simple: A Beginner’s Guide
What is Big O Notation?
Big O Notation is a way to describe how the runtime or memory usage of an algorithm grows as the input size gets larger. It doesn’t care about the speed of your computer or how optimized your Python interpreter is — it focuses purely on the pattern of growth.
In simple words:
Why Should You Care About Big O?
Imagine you’re building a website that handles a few hundred users today but might handle a few million users next year. Choosing an efficient algorithm now can save you from a lot of pain (and costs) later.
Good knowledge of Big O lets you:
Common Time Complexities You’ll See
Code Examples (with Explanations)
Let’s walk through how these complexities show up in actual Python code.
1.O(1) – Constant Time
def get_first_element(lst):
return lst[0]
This operation takes the same amount of time no matter how big the list is.
2.O(n) – Linear Time
Recommended by LinkedIn
def find_element(lst, target):
for item in lst:
if item == target:
return True
return False
You might have to look through the entire list to find what you’re looking for.
3.O(n²) – Quadratic Time
def has_duplicates(lst):
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
if lst[i] == lst[j]:
return True
return False
As you check every pair of items, time grows rapidly as the list gets bigger.
4. O(log n) – Logarithmic Time (Binary Search)
When you have a sorted list, you don’t need to look at every element to find something. You can cut the list in half over and over, which is much faster.
Here’s how Binary Search works:
def binary_search(lst, target):
low = 0
high = len(lst) - 1
while low <= high:
mid = (low + high) // 2
if lst[mid] == target:
return True
elif lst[mid] < target:
low = mid + 1
else:
high = mid - 1
return False
Example usage:
sorted_list = [2, 4, 7, 10, 23, 45, 78]
print(binary_search(sorted_list, 23)) # Output: True
print(binary_search(sorted_list, 5)) # Output: False
Notice that even if the list is 100,000 items long, you’ll only need about 17–18 steps to find the item (or decide it’s not there). That’s the magic of O(log n) time!
Real-World Analogies
A few examples to make it even more relatable:
Quick Revision & Summary
Thanks for sharing, Rupal