Time complexity and big o notation explained for beginners
Understand Big O notation with simple examples: O(1), O(n), O(log n), O(n^2), how to calculate it and how interviewers use it.

Understand Big O notation with simple examples: O(1), O(n), O(log n), O(n^2), how to calculate it and how interviewers use it.

Almost every beginner hits the same wall. Your code works on the sample test, but on the real tests it runs for too long and gets a "Time Limit Exceeded" error. Or an interviewer asks, "What is the time complexity of your solution?" and you freeze.
This guide is time complexity explained in plain language. You will learn what Big O notation means, see the common complexities with small examples, learn how to calculate time complexity step by step, and understand space complexity too. There is also a Big O cheat sheet and a set of practice questions with answers at the end. No advanced maths is needed, just basic loops and functions.
Imagine two programs that both find a name in a list of contacts. On a list of 10 names, both feel instant. On a list of 10 million names, one finishes in a blink and the other takes minutes. The difference is not your laptop. It is the way each program grows as the input gets bigger.
That is what time complexity measures: how the running time of an algorithm grows as the input size grows.
Here is why it matters.
Speed at scale. Code that works for 100 items can fail at 100,000 items. Complexity tells you in advance whether it will.
Coding tests and online judges. Problems come with limits, and a slow solution gets "Time Limit Exceeded" even when the logic is correct.
Interviews. Interviewers almost always ask for the time and space complexity after you write a solution, and they often ask you to improve it.
Real products. Slow code means slow apps, higher server costs and unhappy users.
Better choices. Knowing complexity helps you pick the right data structure, such as an array, a hash map or a tree.
Why not just time the code with a stopwatch? Because running time depends on your machine, your language and what else is running. Complexity ignores all of that and describes the shape of the growth, which is what stays true everywhere.
Big O notation is a way of describing how an algorithm's work grows when the input size (usually called n) grows. It focuses on the biggest factor and ignores small details.
Think of it like travel time. If you walk to a place, the time grows roughly in line with the distance. If you fly, there is a fixed cost for the airport and security, and then distance matters less. Big O captures that growth pattern, not the exact seconds.
Some key ideas:
n is the size of the input. It could be the number of items in a list or the length of a string.
Big O counts steps, not seconds. We count basic operations, such as comparisons and additions.
It describes growth, not exact time. An algorithm that does 3n steps and one that does 100n steps are both O(n), because both grow in a straight line.
We usually talk about the worst case. If a search might find the item on the first try or the last, we describe the last. This gives a safe upper limit.
We drop constants and smaller terms. O(2n + 10) simply becomes O(n), and O(n^2 + n) becomes O(n^2). When n is very large, the biggest term dominates.
You may also hear about best case, average case and worst case. Best case is the luckiest situation, average case is the typical one, and worst case is the unluckiest. In interviews, "time complexity" usually means the worst case unless someone says otherwise.
Here are the complexities you will see most often, from fastest-growing-slowest to slowest. The examples use Python.
O(1): constant time
The work does not depend on the input size.
python
def first_item(arr):
return arr[0]Whether the list has 10 items or 10 million, this takes the same time. Reading an array element by index and looking up a key in a hash map (on average) are also O(1).
O(log n): logarithmic time
The work grows very slowly, because each step cuts the problem in half. Binary search on a sorted list is the classic example.
python
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target:
high = mid - 1
else:
low = mid + 1
return -1With 1,000,000 items, binary search needs only about 20 steps. Any time you halve the input on each step, think O(log n).
O(n): linear time
The work grows in direct proportion to the input. If you double the input, you double the work.
python
def find_max(arr):
best = arr[0]
for x in arr:
if x > best:
best = x
return bestLooping through a list once, searching an unsorted list and summing all items are all O(n).
O(n log n): linearithmic time
A bit slower than linear, but still very practical. Efficient sorting algorithms such as merge sort, and the built-in sort in most languages, are O(n log n).
python
sorted_arr = sorted(arr)Doing something O(log n) for each of n items also gives O(n log n).
O(n^2): quadratic time
The work grows with the square of the input. This usually comes from a loop inside a loop, where both run over the input.
python
def has_pair(arr, target):
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if arr[i] + arr[j] == target:
return True
return FalseIf n doubles, the work becomes four times as much. This is fine for small inputs, but it is often too slow for big ones. Simple sorts like bubble sort and selection sort are O(n^2).
O(2^n): exponential time
The work doubles with each extra item. This often happens with plain recursion that branches twice, like the naive Fibonacci function.
python
def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)This gets slow very quickly, even for small n like 40. Techniques like memoization or dynamic programming can bring it down to O(n).
O(n!): factorial time
The work grows even faster. It appears when you try every possible ordering of n items, such as generating all permutations. It is only workable for very small n.
A quick Big O cheat sheet
From best to worst for large inputs:
O(1): excellent
O(log n): excellent
O(n): good
O(n log n): good
O(n^2): fair for small inputs, risky for big ones
O(2^n): poor
O(n!): very poor
A rough rule of thumb for coding tests: a computer can do around 10 million to 100 million simple operations per second. So if n is up to about 1,000, O(n^2) is usually fine. If n is up to 100,000, you generally need O(n log n) or better. If n is a million, aim for O(n) or O(n log n). Always check the limits in the problem statement.
Complexity of common operations (average cases)
Array: access by index is O(1), searching an unsorted array is O(n), inserting or deleting in the middle is O(n).
Sorted array: binary search is O(log n).
Hash map or set: insert, delete and lookup are O(1) on average.
Linked list: access by position is O(n), inserting at the head is O(1).
Sorting: efficient algorithms are O(n log n).
Binary search tree: operations are about O(log n) if it is balanced.
These are the typical values you will use again and again, so it is worth memorising them.
You do not need a formula. You can work it out by reading the code and following a few simple rules.
Step 1: Decide what n is.
Usually it is the length of the main input, like a list or a string. If there are two inputs, give them different names, such as a and b.
Step 2: Count how many times each part runs.
A single statement is O(1).
A loop that runs n times is O(n).
A loop that halves or doubles its variable each time is O(log n).
Step 3: Add sequential parts, multiply nested parts.
Two separate loops one after another add up, so the cost is O(n) + O(n). Nested loops multiply, so a loop of n inside another loop of n is O(n * n), which is O(n^2).
python
# Two loops in sequence: O(n) + O(n) = O(n)
for x in arr:
print(x)
for x in arr:
print(x * 2)
# Nested loops: O(n) * O(n) = O(n^2)
for x in arr:
for y in arr:
print(x, y)Step 4: Drop the constants.
Three loops of n one after another is O(3n), which is just O(n). A loop that runs exactly 5 times inside a loop of n is O(5n), which is O(n).
Step 5: Keep only the biggest term.
O(n^2 + n + 10) becomes O(n^2), because when n is large, n^2 swamps the rest.
Step 6: Watch for different inputs.
If one loop runs over list a and another over list b, one after the other, the time is O(a + b). If one is nested in the other, it is O(a * b). Do not call both n unless they really are the same size.
Step 7: Check function calls and library functions.
A call to another function costs whatever that function costs. For example, calling sorted() inside a loop that runs n times costs O(n) * O(n log n). Slicing a list, using in on a list, and concatenating strings in a loop can hide extra O(n) work, so check what they cost in your language.
Worked example
python
def count_pairs(arr):
count = 0
n = len(arr)
for i in range(n):
for j in range(i + 1, n):
if arr[i] == arr[j]:
count += 1
return countThe outer loop runs n times. The inner loop runs fewer times each round: n-1, n-2, down to 0. Adding these up gives about n(n-1)/2 steps. Drop the constant and the smaller term, and the result is O(n^2).
How interviewers use this
A common pattern is to start with a simple brute-force solution and then improve it. Take the "two sum" problem, where you must find two numbers that add up to a target:
Brute force: check every pair with two loops. Time is O(n^2) and extra space is O(1).
Better: store seen numbers in a hash map. Time is O(n) and extra space is O(n).
python
def two_sum(nums, target):
seen = {}
for i, x in enumerate(nums):
need = target - x
if need in seen:
return [seen[need], i]
seen[x] = i
return []This is called a time and space trade-off: you spend more memory to save time. Being able to explain it clearly is exactly what interviewers are looking for.
Space complexity measures how much extra memory an algorithm needs as the input grows. It is described with the same Big O notation.
O(1) space: the algorithm uses a fixed amount of extra memory, such as a few variables.
O(n) space: the extra memory grows with the input, such as when you build a new list of size n.
python
# O(1) extra space: only a couple of variables
def total(arr):
s = 0
for x in arr:
s += x
return s
# O(n) extra space: builds a new list
def squares(arr):
return [x * x for x in arr]A few points to remember:
We usually count extra space. The memory used by the input itself is not counted, only what your algorithm adds.
Recursion uses memory. Each recursive call is stored on the call stack. A recursive function that goes n levels deep uses O(n) space, even if it creates no lists.
In-place algorithms change the input directly and use O(1) extra space, such as reversing an array by swapping from both ends.
Hash maps and sets usually cost O(n) space.
Trade-offs are normal. Many fast algorithms use extra memory, and many memory-saving algorithms are slower. In interviews, state both and explain your choice.
Try to work out the time complexity of each snippet before reading the answer.
Question 1
python
def get_last(arr):
return arr[-1]Question 2
python
total = 0
for x in arr:
total += xQuestion 3
python
for i in range(n):
for j in range(n):
print(i, j)Question 4
python
for i in range(n):
print(i)
for j in range(n):
print(j)Question 5
python
i = 1
while i < n:
i = i * 2Question 6
python
for i in range(n):
for j in range(5):
print(i, j)Question 7
python
for i in range(n):
for j in range(i):
print(i, j)Question 8
python
def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)Question 9 (space)
python
def make_squares(arr):
result = []
for x in arr:
result.append(x * x)
return resultAnswers
O(1). Reading the last item takes the same time no matter how long the list is.
O(n). One pass through the list.
O(n^2). Two nested loops that both run n times.
O(n). Two loops in sequence add up to O(2n), which simplifies to O(n).
O(log n). i doubles each time, so the loop runs about log n times.
O(n). The inner loop always runs exactly 5 times, which is a constant, so the total is O(5n) = O(n).
O(n^2). The inner loop runs 0, 1, 2, up to n-1 times, which adds up to about n(n-1)/2, and that simplifies to O(n^2).
O(2^n). Each call makes two more calls, so the number of calls roughly doubles with each level. This is why naive recursive Fibonacci is slow.
Time O(n), space O(n). The new list grows to the same size as the input.
If you got most of these right, you already understand the core of Big O.
What is Big O notation in simple words?
It is a way to describe how the running time (or memory use) of an algorithm grows as the input gets bigger. It ignores small details and focuses on the overall growth pattern.
What is the difference between time complexity and space complexity?
Time complexity is about how much time (steps) an algorithm needs. Space complexity is about how much extra memory it needs. Both are written using Big O notation.
Is O(n log n) better than O(n^2)?
Yes. For large inputs, O(n log n) grows much more slowly. For example, with a million items, n^2 is a trillion steps, while n log n is only about 20 million.
Why do we ignore constants in Big O?
Because Big O describes the growth trend for large inputs. Whether an algorithm does n steps or 5n steps, doubling the input still doubles the work. Constants matter in real performance, but they are not part of the notation.
Is Big O always the worst case?
Usually, when people say "the time complexity is O(...)", they mean the worst case. Strictly speaking, Big O is an upper bound, and there are other notations (Omega for a lower bound and Theta for a tight bound), but for most interviews, worst-case Big O is what you need.
What is the time complexity of searching in a list or a hash map?
Searching an unsorted list is O(n). Binary search on a sorted list is O(log n). Looking up a key in a hash map is O(1) on average.
What is the time complexity of sorting?
Efficient algorithms like merge sort and the built-in sort in most languages run in O(n log n). Simple algorithms like bubble sort and selection sort are O(n^2).
How do I find the time complexity of recursive code?
Count how many calls are made and how much work each call does. A function that calls itself once with a smaller input (like factorial) is usually O(n). One that calls itself twice (like naive Fibonacci) is about O(2^n). One that halves the input each time (like binary search) is O(log n).
How much Big O do I need for interviews?
You should be able to state the time and space complexity of every solution you write, recognise the common ones (O(1), O(log n), O(n), O(n log n), O(n^2)) and explain how you could improve a slower solution.
Understanding Big O is mostly a matter of habit. After you solve any problem, ask yourself two questions: "What is the time complexity?" and "What is the space complexity?" Write down the answers, and check them against the solutions. After a couple of weeks, it will feel natural.
Practise estimating complexity on beginner problems on The Zift.