What is Big O Notation?
Complexity·7 min·Python code
Big O notation tells you how the cost of an algorithm climbs when its input grows. It names the dominant trend, like O(n) for linear or O(n^2) for quadratic, so you can compare algorithms on any hardware.
Why Big O Tracks Growth Instead of Seconds
Big O does not measure speed in seconds. New laptops and old phones finish the same loop at very different times, yet both slow down in the same way as the input grows. Big O drops hardware, language and constant factors, and keeps one thing, the shape of the curve between input size and work done.
That shape makes Big O useful. On a handful of items, an O(n) algorithm can lose to an O(n^2) algorithm, but as the input grows the O(n) algorithm pulls ahead and stays ahead. Big O answers the question real systems ask. When the data grows ten or a thousand times, does the cost rise gently or explode?
Common Big O Complexity Classes From O(1) to O(2^n)
Most interviews need only a short list of classes. O(1) means constant time, a fixed amount of work whatever the input, like indexing an array. O(log n) means logarithmic time, where every step halves the problem, like binary search on a sorted array.
O(n) means linear time, one pass over n items. O(n log n) is the cost of efficient comparison sorts like merge sort and heapsort, and it is the practical floor for general sorting.
Higher classes get costly quickly. O(n^2) means quadratic time, which a loop inside another loop over the same data creates, like a naive all pairs comparison. O(2^n) means exponential time, which appears when you list every subset or write naive recursive Fibonacci that solves the same subproblems again, and one extra element roughly doubles the work.
Spotting your code's class, and the line or branch that drives it, is the core skill.
How to Simplify Big O Expressions
Keep the fastest growing term and drop constant multipliers. Loops that do 3n + 5 operations are O(n), and functions that take n^2 + n steps are O(n^2), because the n^2 term dwarfs everything else when n is large. That is why O(n) and O(500n) share one class.
Formally, Big O is an upper bound. Saying f(n) = O(g(n)) means f stays below some constant multiple of g once n is large enough. Most interview answers describe the worst case, but you can describe any case.
Big Theta is the tight bound, where growth matches g from above and below, and Big Omega is the lower bound. Learn both names, even though everyone says Big O day to day.
Big O Code Example in Python
def has_duplicate(nums):
"""Return True if any value appears more than once."""
seen = set()
for n in nums: # loops at most len(nums) times, so O(n)
if n in seen: # set membership is O(1) on average
return True
seen.add(n)
return False
# Brute force version, shown for contrast:
# for i in range(len(nums)):
# for j in range(i + 1, len(nums)): # nested loop, so O(n^2)
# if nums[i] == nums[j]:
# return True
Test the code in CodeStory's browser IDE, free on the platform. Open the CodeStory App
Time and Space Complexity of the Example
| Time | O(n) on average for the hash set version, O(n^2) for the brute force nested loop |
|---|---|
| Space | O(n) for the set, O(1) for the brute force version |
The shortest path costs O(1) when a duplicate sits at the start and the function returns early. Set lookups cost O(1) on average but can fall to O(n) with heavy hash collisions, so the strict worst case is O(n^2).
When to Use Big O
- Compare two approaches before you write code, because Big O shows which one scales to your input size.
- Check whether brute force will pass the limits, since n up to 10^5 rules out an O(n^2) approach on most judges.
- Explain your solution's efficiency out loud in a coding interview.
- Find out why code passes small tests but crawls on large inputs.
Mistakes to Avoid
- Big O ignores constant factors and small inputs, so an O(n log n) algorithm can lose to an O(n^2) algorithm when n is tiny.
- Slicing a list, copying an array or joining strings inside a loop adds a factor of n you did not count.
- Hash map and set operations cost O(1) on average, but collisions can push them to O(n) in the worst case. Ignoring space complexity is just as common a slip.
Big O Notation FAQs
Is Big O notation hard to learn?
No. Big O describes how work grows as input grows, and that idea is plain. Dropping constants and lower order terms trips people up, and so does analysing loops and recursion. Working through a handful of examples builds comfort.
What is the time complexity of a nested loop?
O(n^2) when both loops go over the same input about n times, because every outer step does n inner steps. If the inner loop repeats a fixed number of times, the total stays O(n). Check what both loops iterate over before you call it quadratic.
What is the difference between Big O and Big Theta?
Big O is an upper bound, so the algorithm grows no faster than that rate. Big Theta is a tight bound, so growth matches the rate from above and below. People say Big O even when they mean a tight bound, but knowing the difference shows depth.
Do I need Big O for coding interviews?
Yes. Interviewers expect time and space analysis in almost every technical round, and they often ask you to improve a solution's Big O. You need no heavy math. Spot the dominant cost, state it in terms of the input and explain the trade offs.
What is the difference between time complexity and space complexity?
Time complexity measures how the number of steps grows with input size, and space complexity measures how extra memory grows. Hash sets in the code example cost O(n) time on average and O(n) space, while nested loops cost O(n^2) time and O(1) space.
Why does Big O drop constants?
Constants stop mattering as the input grows. Both 3n + 5 and 500n grow in a straight line, so both belong to O(n).
How do I practise Big O after this guide?
Open CodeStory's DSA practice problems, write a brute force answer first, then improve it and state both costs. Then take a spoken mock round to test whether you can explain them.
Related Guides
Guides are step one. In a CodeStory batch you build, say your answer out loud in a scored mock round and hear what an interviewer thinks.
Talk to a Mentor