Big O Notation Examples
Big O Notation and Time Complexity Analysis
Introduction
Big O notation is a fundamental tool for analyzing the efficiency of algorithms, data structures, and code segments. It helps programmers decide which solution is more efficient by estimating how the runtime scales with input size, focusing on the worst-case scenario for very large inputs.
What Is Big O Notation?
Big O notation estimates the number of operations required by an algorithm in relation to the size of its input.
It provides a relative measure of runtime growth, not an exact count of seconds or operations.
The notation uses n to represent the size of the input (e.g., length of a list, number of elements).
The goal is to find a simplified function g(n) such that the actual operation count f(n) is bounded above by c⋅g(n) for all large n.
Definition: f(n)=O(g(n)) if there exist constants c>0 and n0≥1 such that f(n)≤c⋅g(n) for all n≥n0.
Why It Matters
Two algorithms can solve the same problem, but one may be vastly slower for large inputs.
Without Big O, predicting performance on large data is guesswork.
Inefficient code may work for small inputs but become infeasible (years/decades) when scaled.
The Mathematical Definition in Practice
To find the Big O of an algorithm:
Count the approximate number of operations f(n).
Find a simple function g(n) and constants c, n0 that satisfy the inequality.
The chosen g(n) is the Big O notation.
Example: For a loop over n items performing two operations inside the loop plus one initialization:
We claim f(n)=O(n) because:
Choose c=3, n0=1.
For n≥1: 2n+1≤3n (holds for n=1: 3≤3; grows).
Thus O(n) is correct.
Key point: We ignore constants and lower-order terms because they become negligible as n grows large.
Simplifying to Find Big O
Rules for Sums (Additive Terms)
When f(n) is a sum of terms (e.g., 2n2+n+1):
The term with the highest growth rate dominates.
Remove constants and lower-order terms.
Example: f(n)=2n2+n+1
For large n, n2 dwarfs n and 1.
Hence f(n)=O(n2).
Proof sketch: Choose c=1000, then 2n2+n+1≤1000n2 for all n≥1.
General approach: If the largest term is ank, then O(nk). Drop the constant a.
Rules for Products (Multiplicative Terms)
When f(n) is a product (e.g., 3n⋅log2n2):
Remove constants.
Simplify inside logarithms using exponent rules:
log2n2=2log2n (an exponent becomes a multiplier).
The constant multiplier from logs can also be removed.
Example: f(n)=3n⋅log2n2
Remove 3: n⋅log2n2=n⋅(2log2n)=2nlog2n
Remove 2: nlog2n
Cannot simplify further because terms are multiplied, not added.
Result: O(nlogn).
Caution: For products, both factors affect runtime; you cannot simply drop the smaller factor as you do with sums.
Common Big O Functions (Complexity Chart)
Functions are ordered from best (fastest) to worst (slowest):
O(1) – Constant time: Independent of input size. Example: checking if a number is odd/even.
O(logn) – Logarithmic time: Grows slowly. Doubling the input adds a constant number of steps. Example: binary search.
O(n) – Linear time: Runtime scales directly with input size. Example: summing all elements in a list.
O(nlogn) – Log-linear time: Common in efficient sorting (e.g., mergesort).
O(n2) – Quadratic time: Nested loops over the same data. Example: bubble sort.
O(2n) – Exponential time: Every increase in n doubles the runtime. Example: naive Fibonacci recursion.
O(n!) – Factorial time: Extremely poor scalability. Example: generating all permutations.
Examples: Step-by-Step Time Complexity Analysis
Example 0 – Constant Time (O(1))
def is_even(num):
return num % 2 == 0Operations: A single modulus and comparison – independent of the value of
num(n).Big O: O(1).
Example 1 – Linear Time (O(n))
def sum_list(nums):
total = 0
for number in nums:
total += number
return totaltotal = 0: 1 operation.Loop runs n times (where n= length of
nums).Inside loop: one addition per iteration → n operations.
Total: n+1. Remove constant → O(n).
Example 2 – Quadratic Time (O(n2))
def find_duplicates(nums):
result = []
for _ in range(len(nums)):
result.append(1) # O(n)
for i in range(len(nums)): # O(n)
for j in range(len(nums)): # O(n) inside O(n)
if nums[i] == nums[j]:
result.append(nums[i])
return resultFirst loop: n operations.
Nested loops: outer runs n times, inner runs n times for each outer iteration → n×n=n2 iterations.
Inside inner loop: constant work (comparison and maybe append).
Total operations ≈ n+3n2 (constants approximate). The dominant term is n2.
Big O: O(n2).
Example 3 – Two Inputs (O(n+m))
def process_two_lists(nums1, nums2):
result = []
for num in nums1:
result.append(num)
for num in nums2:
result.append(num * 2)
return resultLet n= length of
nums1, m= length ofnums2.First loop: n operations.
Second loop: m operations.
Total: n+m (plus constants, ignored).
Big O: O(n+m). (Cannot combine into a single variable because inputs are independent.)
Example 4 – Nested Lists (O(h⋅w))
def sum_nested(nested_list):
total = 0
for inner in nested_list: # h = number of inner lists
for value in inner: # w = number of elements per inner list
total += value
for value in inner: # second traversal of same list
total += value * 2
for value in inner: # third traversal
total += value * 3
return totalHeight h= number of inner lists.
Width w= number of elements in each inner list (assume equal for worst-case).
Outer loop: h iterations.
Each inner list traversed three times → 3w operations per outer iteration.
Total: h⋅3w. Remove constant → O(h⋅w) (often written as O(n⋅m) for generic dimensions).
Example 5 – Recursive Fibonacci (O(2n))
def fibonacci(n):
if n <= 2:
return 1
return fibonacci(n-1) + fibonacci(n-2)Inside function: constant time (base case check and addition).
Each call spawns two recursive calls, each with input reduced by a constant (1 or 2).
This forms a binary recursion tree with height approximately n.
Number of calls grows exponentially: 2n (ignoring lower-order terms).
Big O: O(2n).
Example 6 – Built-in Functions and Worst Case (O(n+m))
def check_max_in_search(lst, search_list):
max_val = max(lst) # O(n) – finding max scans entire list
for value in search_list: # O(m)
if max_val == value:
return True
return Falsemax()iterates through all elements oflst(size n) → O(n).Loop over
search_list(size m) → O(m).Worst case: value not found, full traversal.
Total: O(n+m).
Example 7 – Recursive Halving (O(logn))
def recursive_half(n):
if n < 1:
return
print(n)
recursive_half(n // 2)One recursive call per function invocation.
Input is divided by 2 each time (integer division).
Number of calls equals the number of times you can halve n until reaching 0: ⌊log2n⌋.
Inside each call: constant work.
Big O: O(logn) (base 2 log, but constant base omitted in Big O).
Example 8 – Strings of Varying Length (O(n⋅klogk))
def process_strings(strings):
n = len(strings)
for s in strings: # n iterations
for char in s: # k iterations (max string length)
if char in "aeiou":
# do something constant
if len(s) > len(s)//2:
sorted_s = sorted(s) # O(k log k)Let n= number of strings, k= length of the longest string.
Outer loop: n iterations.
Inner loop over characters: k iterations (worst-case).
Sorting inside the conditional: worst-case klogk per outer iteration.
Total work per outer iteration: k+klogk=k(1+logk). Dominant term klogk.
Multiply by n: O(n⋅klogk).
Example 9 – Multiple Variables and Complex Loop (O(nlogn+mlogm+(n+m)⋅k))
(Skipped in video due to complexity, but an advanced example involving dictionaries, sorting, and a while loop processing strings character by character)
Key idea: Different inputs (dictionary sizes n and m, longest string length k) combine additively or multiplicatively depending on nesting. The final complexity includes terms for sorting (nlogn, mlogm) and a while loop that pops from the front of a list (O(list length)) and appends truncated strings.
Example 10 – (Skipped)
Example 11 – Triple Nested Loop (O(n3))
def sum_suffix_sums(nums):
n = len(nums)
sum_to_end = []
count = 0
for i in range(n): # n
sum_to_end.append(0)
for j in range(i+1, n): # approximately n - i iterations
sum_to_end[i] += nums[j]
for k in range(len(sum_to_end)): # grows from 1 to n
count += 1Outer loop: n iterations.
First inner loop: runs about n,n−1,n−2,…,1 times → total 2n(n−1)=O(n2).
Second inner loop: runs 1,2,3,…,n times → also O(n2).
Combining nested structures: the loops are nested inside the outer n, so overall operations are n⋅O(n)⋅O(n)=O(n3).
Big O: O(n3).
Example 12 – Recursive Factorial (O(n!))
def example12(n):
if n == 1:
return 1
total = 0
for _ in range(n):
total += example12(n-1)
return totalFor input n, the function makes n recursive calls to n−1.
Each of those n−1 calls makes (n−1) calls to n−2, and so on.
The recursion tree has n branches at the root, n−1 at the next level, etc.
Total number of recursive calls (including leaves) is bounded by 2⋅n! (the base case occurs n! times). Removing the constant yields n!.
Big O: O(n!) – factorial time, one of the worst complexities.
These examples cover the essential patterns: constant, linear, quadratic, logarithmic, log-linear, exponential, factorial, and those involving multiple independent variables. Understanding how to count operations and apply simplification rules enables you to analyze the time complexity of any algorithm.

Ask anything
We've read this whole study set, so questions about it get the best answers.