Big O notation is the language we use to describe algorithm efficiency. Master it and you'll think clearly about any coding problem.
Big O notation describes how the runtime or memory usage of an algorithm grows relative to the input size. It answers: "If I double the input, what happens to the time/memory?"
It focuses on the worst case and dominant terms — we drop constants and lower-order terms.
f(n) = 3n² + 5n + 100 → O(n²)
Two solutions can both be "correct" but one might take 1ms and the other 10 minutes on large inputs. Big O helps you reason about this before writing a single line of code.
Runtime doesn't change regardless of input size.
def get_first(arr):
return arr[0] # always one operationInput is halved each step. Very efficient.
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target: return mid
elif arr[mid] < target: left = mid + 1
else: right = mid - 1One operation per element.
def find_max(arr):
max_val = arr[0]
for num in arr: # n iterations
if num > max_val:
max_val = num
return max_valTypical of efficient sorting algorithms.
# Merge sort, heap sort, Python's sorted()
sorted_arr = sorted(arr) # O(n log n)Nested loops over the same input.
def bubble_sort(arr):
for i in range(len(arr)): # n
for j in range(len(arr)-1): # n
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]Each step doubles the work. Avoid for large inputs.
def fibonacci(n):
if n <= 1: return n
return fibonacci(n-1) + fibonacci(n-2) # two recursive calls each timeO(2n) → O(n)
O(500) → O(1)
O(n² + n) → O(n²)
O(n + log n) → O(n)
def func(a, b):
for x in a: # O(a)
print(x)
for y in b: # O(b)
print(y)
# Total: O(a + b), NOT O(n)for i in arr: # O(n)
for j in arr: # O(n)
... # O(n²) totalSpace complexity measures extra memory used (not counting the input itself).
def sum_list(arr):
total = 0 # O(1) space — just one variable
for n in arr:
total += n
return total
def double_list(arr):
result = [] # O(n) space — new list same size as input
for n in arr:
result.append(n * 2)
return result| Operation | Array | Linked List | Hash Table | BST |
|---|---|---|---|---|
| Access | O(1) | O(n) | O(1) | O(log n) |
| Search | O(n) | O(n) | O(1) | O(log n) |
| Insert | O(n) | O(1) | O(1) | O(log n) |
| Delete | O(n) | O(1) | O(1) | O(log n) |