Big-O notation & complexity analysis
Computer Science · Algorithms
Question 1 of 10
0n = 18 total = 0 for i in range(0, n, 6): total += 1 How many times does the loop body run?
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Big-O notation & complexity analysis explained
Big O notation describes how an algorithm's running time (or memory use) grows as the input size grows. It ignores constant factors and smaller terms, because for large inputs the fastest-growing term dominates: an algorithm taking steps is .
Common classes, from fastest to slowest growth:
- , constant: accessing an array element by its index.
- , logarithmic: binary search, which halves the search space each step.
- , linear: a single loop over every element, like a linear search.
- : efficient sorting algorithms such as merge sort.
- , quadratic: two nested loops over the input, as in bubble sort.
- , exponential: trying every subset of the input.
To analyse code, count how the number of basic steps depends on . Sequential blocks add (and you keep the largest); nested loops multiply. Big O usually describes the worst case unless stated otherwise.
Worked example
What is the time complexity of this code?
for i in range(n):
for j in range(n):
total += i * j
for k in range(n):
print(k)
- The nested loops run times.
- The final loop runs times.
- Total: steps. Drop the smaller term: .
Doubling roughly quadruples the running time of the nested part. For 1,000 items that is about a million steps, while an approach needs only around 10,000.
Longer guide: How to use Big-O notation
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
n = 28 total = 0 for i in range(0, n, 4): total += 1
How many times does the loop body run?
Medium
n = 25 count = 0 for i in range(n): for j in range(i): count += 1
What is the final value of count?
Hard
What is the time complexity of this code, in Big-O terms of m? total = 0 for i in range(m): for j in range(4): total += 1
- O(log n)
- O(n log n)
- O(1)
- O(n)