Ankit KanojiyaBeginner

Evergreen guide by Ankit Kanojiya · Beginner · DSA

Big-O Notation and Complexity Analysis Made Simple

A practical introduction to Big-O notation that explains how to reason about time and space cost without heavy math. Covers common growth classes and how to analyze real code.

Big-O notation describes how the running time or memory use of an algorithm grows as the input size grows. It ignores machine speed and constant factors so two implementations can be compared on the same footing. The goal is not an exact instruction count but an honest picture of how an algorithm behaves when the input gets large.

Why Growth Rate Matters

On ten elements almost anything is fast. The differences appear at scale. An algorithm that does roughly n operations and one that does n squared operations may both finish instantly on 100 items, but on one million items the second does a trillion operations while the first does a million. Big-O captures that gap.

Formally, a function is O(g(n)) if beyond some input size it stays below a constant multiple of g(n). In practice this means keep the fastest growing term and drop constants and lower-order terms. So 3n + 50 becomes O(n), and 2n squared + 10n becomes O(n squared).

The Common Classes

Ordered from fastest to slowest growth:

  • O(1) constant: cost does not depend on input size, such as reading an array index.
  • O(log n) logarithmic: the input is repeatedly halved, as in binary search.
  • O(n) linear: a single pass over the data.
  • O(n log n): efficient sorting such as mergesort and heapsort.
  • O(n squared) quadratic: nested loops over the same data.
  • O(2^n) exponential and O(n!) factorial: brute-force over all subsets or permutations.

A useful reference point: log base 2 of one million is about 20, so an O(log n) step count stays tiny even for huge inputs.

Analyzing Code

The mechanical approach is to count how many times the innermost work runs as a function of n.

def has_duplicate(nums):
    # O(n^2): for each item, scan the rest
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] == nums[j]:
                return True
    return False

The outer loop runs n times and the inner loop runs up to n times, so the total is proportional to n squared. A set turns this into a single pass:

def has_duplicate_fast(nums):
    # O(n) time, O(n) space
    seen = set()
    for x in nums:
        if x in seen:
            return True
        seen.add(x)
    return False

Set membership is O(1) on average, so the whole function is O(n). The trade is extra memory for the set, which is where space complexity enters.

Sequential Versus Nested Work

Two loops one after another add, two loops nested multiply.

# O(n) + O(n) = O(n)
for x in nums: process(x)
for x in nums: process(x)

# O(n) * O(n) = O(n^2)
for x in nums:
    for y in nums:
        pair(x, y)

When a loop halves the remaining range each step, the count is logarithmic:

def binary_search(sorted_nums, target):
    lo, hi = 0, len(sorted_nums) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if sorted_nums[mid] == target:
            return mid
        if sorted_nums[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

Each iteration discards half the candidates, so at most log base 2 of n iterations run. That is O(log n).

Best, Average, and Worst Case

Big-O usually refers to the worst case, the upper bound on cost. The average case can differ. Hash lookups are O(1) on average but O(n) in a rare worst case with many collisions. Quicksort is O(n log n) on average but O(n squared) when pivots are chosen poorly. State which case is meant when it matters.

Space Complexity

The same notation applies to memory beyond the input. A recursive function that goes n levels deep uses O(n) stack space even if it allocates nothing else. Building a hash set of all elements is O(n) space. Reversing an array in place is O(1) extra space.

Common Pitfalls

  • Dropping a hidden loop. Slicing or concatenating inside a loop can turn linear code into quadratic.
  • Treating string concatenation in a loop as free. In many languages it copies the whole string each time.
  • Ignoring the cost of library calls. Sorting inside a loop multiplies an n log n cost by the loop count.

Worked Example

Consider summing the digits of every number from 1 to n. There are n numbers and each has about log(n) digits, so the total work is O(n log n), not O(n). Counting the inner work carefully is what separates a correct analysis from a guess. With these rules the growth class of most everyday code can be read directly off its loops and recursion.