Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

Big O Notation Explained: Time and Space Complexity for Beginners

Understand Big O notation with simple examples: O(1), O(log n), O(n), O(n log n), O(n²) and O(2ⁿ), how to calculate complexity from code, space complexity, amortized analysis and common data structure costs.

Sumit KumarUpdated Oct 11, 20265 min readDSA
Big O Notation Explained: Time and Space Complexity for Beginners

Big O notation describes how the running time or memory of an algorithm grows as the input gets bigger. It doesn't measure seconds. Instead, it answers "if I double the input, how much more work does this do?" That's why it's the common language for comparing algorithms in interviews and code reviews.

Why not just time the code?#

Actual run time depends on your machine, language, compiler and what else is running. Big O ignores those details and focuses on the growth rate. An O(n²) algorithm might be fast for 100 items, but for 1,000,000 items it will lose to an O(n log n) algorithm on any computer.

The common complexity classes#

Big O complexity chart comparing growth of O(1), O(log n), O(n), O(n log n), O(n squared) and O(2 to the n) as input size increases
Big ONamen = 1,000Example
O(1)Constant1Array index, hash map lookup
O(log n)Logarithmic~10Binary search
O(n)Linear1,000Loop through a list
O(n log n)Linearithmic~10,000Merge sort, efficient sorting
O(n²)Quadratic1,000,000Nested loops over the same data
O(2ⁿ)ExponentialastronomicalAll subsets, naive recursion
O(n!)FactorialastronomicalAll permutations

O(1): constant time#

Python
def get_first(items):
    return items[0]           # one step, no matter how long the list is

prices = {"apple": 120}
prices["apple"]               # average O(1) hash lookup

O(log n): logarithmic time#

Each step cuts the problem in half. Doubling the input adds just one more step.

Python
def count_halvings(n):
    steps = 0
    while n > 1:
        n //= 2
        steps += 1
    return steps              # count_halvings(1_000_000) == 19

See binary search for the classic O(log n) algorithm.

O(n): linear time#

Python
def find_max(nums):
    best = nums[0]
    for x in nums:            # touches every element once
        if x > best:
            best = x
    return best

O(n log n): linearithmic time#

Python
def merge_sort(a):
    if len(a) <= 1:
        return a
    mid = len(a) // 2
    left, right = merge_sort(a[:mid]), merge_sort(a[mid:])   # log n levels
    merged, i, j = [], 0, 0
    while i < len(left) and j < len(right):                  # n work per level
        if left[i] <= right[j]:
            merged.append(left[i]); i += 1
        else:
            merged.append(right[j]); j += 1
    return merged + left[i:] + right[j:]

Most good sorting algorithms (merge sort, heap sort, Python's Timsort, Java's sort for objects) are O(n log n).

O(n²): quadratic time#

Python
def has_duplicate_slow(nums):
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):   # nested loop over the same data
            if nums[i] == nums[j]:
                return True
    return False

def has_duplicate_fast(nums):             # O(n) with a set
    return len(set(nums)) != len(nums)

O(2ⁿ): exponential time#

Python
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)        # each call branches into two

from functools import lru_cache

@lru_cache(maxsize=None)
def fib_memo(n):                          # memoization → O(n)
    return n if n < 2 else fib_memo(n - 1) + fib_memo(n - 2)

fib(40) makes over 300 million calls; fib_memo(40) makes 41. Spotting and removing repeated work like this is the heart of dynamic programming.

How to calculate Big O#

Rule 1: drop constants#

Python
for x in nums: print(x)       # n
for x in nums: print(x * 2)   # n
# total 2n → O(n)

Rule 2: keep only the dominant term#

O(n² + n + 100) becomes O(n²), because for large n the n² term swamps the rest.

Rule 3: sequential steps add, nested steps multiply#

Python
for a in A:          # O(a)
    pass
for b in B:          # O(b)   → together O(a + b)
    pass

for a in A:
    for b in B:      # O(a × b)
        pass
Different inputs, different letters

If a function loops over two different arrays, the answer is O(a + b) or O(a·b), not O(n) or O(n²). Using one letter for both is a common interview mistake.

Rule 4: watch for hidden loops#

Python
for word in words:
    if word in banned_list:     # 'in' on a list is O(m) → whole loop is O(n·m)
        ...
result = ""
for s in parts:
    result += s                 # string concatenation copies → can be O(n²)
"".join(parts)                  # O(n)

Library calls like list.index, list.remove, slicing and sorted all have their own cost.

Rule 5: recursion = calls × work per call#

Recursion patternComplexity
One call on n − 1, O(1) workO(n)
One call on n / 2, O(1) workO(log n)
Two calls on n / 2, O(n) work (merge sort)O(n log n)
Two calls on n − 1, O(1) work (naive Fibonacci)O(2ⁿ)

Space complexity#

Space complexity measures extra memory used, excluding the input.

Python
def total(nums):              # O(1) space: one variable
    s = 0
    for x in nums:
        s += x
    return s

def squares(nums):            # O(n) space: a new list
    return [x * x for x in nums]

def depth(n):                 # O(n) space: n stack frames
    return 0 if n == 0 else 1 + depth(n - 1)

Recursion depth counts as space. This is why the recursive linked list reversal uses O(n) space while the iterative version uses O(1).

Best, average and worst case#

  • Quick sort: O(n log n) on average, O(n²) in the worst case (bad pivots).
  • Hash map lookup: O(1) on average, O(n) in the worst case (many collisions).
  • Linear search: O(1) best case (first item), O(n) worst case.

When people say "Big O", they usually mean the worst case unless they say otherwise.

Amortized complexity#

A dynamic array (Python list, Java ArrayList) occasionally has to copy everything into a bigger array, which is O(n). But it doubles in size each time, so those copies are rare. Averaged over many appends, each append costs O(1). This is called amortized O(1).

Cheat sheet: common operations#

StructureAccessSearchInsertDelete
Array / listO(1)O(n)O(n) (O(1) amortized at end)O(n)
Linked listO(n)O(n)O(1) at known nodeO(1) at known node
Hash map / setn/aO(1) avgO(1) avgO(1) avg
Balanced BST (TreeMap)O(log n)O(log n)O(log n)O(log n)
Binary heapO(1) min/maxO(n)O(log n)O(log n)
Stack / queueO(1) top/frontO(n)O(1)O(1)

What input size can you handle?#

A typical judge runs about 10⁸ simple operations per second. Use the input limits to guess the required complexity:

n up toTarget complexity
10–12O(n!)
20–25O(2ⁿ)
500O(n³)
5,000O(n²)
10⁶O(n log n)
10⁸O(n) or O(log n)
Interview tip

Always state the time and space complexity of your solution before the interviewer asks. Then ask yourself whether a hash map, sorting, two pointers or a sliding window could bring it down a level.

Key takeaways#

  • Big O describes how work grows with input size, not actual seconds.
  • From fastest to slowest: O(1), O(log n), O(n), O(n log n), O(n²), O(2ⁿ), O(n!).
  • Drop constants and smaller terms; add sequential steps and multiply nested ones.
  • Count hidden costs in library calls and recursion depth for space.
  • Use input limits to predict the complexity a problem expects.