Time complexity tells you how the work done by a program grows when you give it more input. Big O notation is the short way of writing that growth, such as O(1), O(n) or O(n²). It counts steps, not seconds, so the answer is the same on a slow laptop and a fast server.
This page shows you how to count steps in loops and read the common Big O values. There is no heavy maths, only small examples in Java and Python.
Why we need time complexity
Suppose two students write code to search for a roll number in a list. Both programs work. On a list of 10 names, both finish instantly. On a list of 10 lakh names, one finishes at once and the other takes much longer.
Measuring seconds is not a fair test. It depends on the computer, the language and what else is running. Instead, we ask a simpler question:
If the input gets bigger, how fast does the number of steps grow?
That growth is the time complexity. We use n for the size of the input, such as the number of items in an array.
Counting steps in loops
The trick is to count how many times the most repeated line runs.
No loop
def first(nums):
return nums[0]
One step, whether the list has 5 items or 5 lakh. The work does not depend on n.
One loop
def total(nums):
s = 0
for x in nums:
s += x
return s
The line s += x runs once per item. For n items, it runs n times.
A loop inside a loop
def print_pairs(nums):
for a in nums:
for b in nums:
print(a, b)
For each of the n values of a, the inner loop runs n times. That is n x n = n² prints.
A loop that halves
def halve(n):
steps = 0
while n > 1:
n = n // 2
steps += 1
return steps
Each pass cuts n in half. Starting from 1000, the values are 500, 250, 125, 62, 31, 15, 7, 3, 1. That is 9 passes. The number of halvings needed is about log₂ n.
See the growth for yourself
This program counts the steps for each pattern:
def count_linear(n):
steps = 0
for i in range(n):
steps += 1
return steps
def count_quadratic(n):
steps = 0
for i in range(n):
for j in range(n):
steps += 1
return steps
def count_halving(n):
steps = 0
while n > 1:
n = n // 2
steps += 1
return steps
for n in [10, 100, 1000]:
print(n, count_linear(n), count_quadratic(n), count_halving(n))
Output:
10 10 100 3
100 100 10000 6
1000 1000 1000000 9
Read each row: when n goes from 100 to 1000 (10 times bigger), the single loop does 10 times more steps, the nested loop does 100 times more, and the halving loop adds only 3 steps.
The common Big O values
| Big O | Name | What it means | Example |
|---|---|---|---|
| O(1) | Constant | Same work for any n | Read arr[3], push to a stack |
| O(log n) | Logarithmic | Work grows very slowly | Binary search on sorted data |
| O(n) | Linear | Work grows in step with n | One loop over an array, linear search |
| O(n log n) | Linearithmic | A bit more than linear | Merge sort |
| O(n²) | Quadratic | Work grows with n x n | Two nested loops over the same data, bubble sort |
| O(2ⁿ) | Exponential | Work doubles with each extra item | Simple recursive Fibonacci |
From fastest growing to slowest, for big n:
O(1) < O(log n) < O(n) < O(n log n) < O(n^2) < O(2^n)
Steps for different n
| n | log₂ n (about) | n | n log₂ n (about) | n² |
|---|---|---|---|---|
| 10 | 3 | 10 | 33 | 100 |
| 1,000 | 10 | 1,000 | 10,000 | 10,00,000 |
| 10,00,000 | 20 | 10,00,000 | 2,00,00,000 | 1,00,00,00,00,00,000 |
At n = 10, all of them are small. At n = 10 lakh, O(n²) needs about 10¹² steps, which is far too slow, while O(log n) needs about 20. This is why complexity matters for big data.
O(1), O(n) and O(n²) in Java
public class BigO {
// O(1): one step, no matter how long the array is
static int first(int[] nums) {
return nums[0];
}
// O(n): visits each element once
static int sum(int[] nums) {
int total = 0;
for (int x : nums) {
total += x;
}
return total;
}
// O(n^2): compares every pair
static boolean hasDuplicate(int[] nums) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] == nums[j]) {
return true;
}
}
}
return false;
}
public static void main(String[] args) {
int[] nums = {4, 8, 15, 16, 23, 42, 8};
System.out.println(first(nums));
System.out.println(sum(nums));
System.out.println(hasDuplicate(nums));
}
}
Output:
4
116
true
In hasDuplicate, the inner loop starts at i + 1, so it does about n²/2 comparisons, not n². Big O still calls this O(n²), as the next section explains.
Three simple rules
Rule 1: Drop constants
A loop that does 3 things per item takes 3n steps. Big O writes it as O(n). Constants do not change the shape of the growth. Likewise, n²/2 becomes O(n²).
Rule 2: Keep the biggest term
If code has one loop (n) followed by a nested loop (n²), the total is n² + n. For large n, n² is far bigger, so we write O(n²).
Rule 3: Different inputs get different letters
def print_both(a, b):
for x in a:
print(x)
for y in b:
print(y)
If a has n items and b has m items, this is O(n + m), not O(n). A loop over a with a nested loop over b is O(n x m).
Common mistake: Calling every nested loop O(n²). If the inner loop always runs a fixed 5 times, the code is O(5n), which is O(n). Count what the inner loop really depends on.
Best, average and worst case
Linear search checks items one by one until it finds the target.
| Case | When | Steps |
|---|---|---|
| Best | Target is the first item | 1 |
| Average | Target is somewhere in the middle | about n/2 |
| Worst | Target is last or missing | n |
When people say "linear search is O(n)", they mean the worst case. In interviews, give the worst case unless asked otherwise, and mention the best case if it is very different.
Space complexity basics
Space complexity is the same idea for extra memory.
- A few variables, whatever the input size: O(1) space.
- A new array or set that holds up to n items: O(n) space.
- A recursive function that goes n calls deep: O(n) space, because each call sits on the call stack. See what is recursion.
Often you can trade memory for time. This Python version of the duplicate check uses a set:
def has_duplicate(nums):
seen = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return False
print(has_duplicate([4, 8, 15, 16, 23, 42, 8])) # True
print(has_duplicate([1, 2, 3])) # False
Checking a set takes O(1) time on average, so this version is O(n) time instead of O(n²). The cost is O(n) extra space for the set.
| Version | Time | Extra space |
|---|---|---|
| Nested loops | O(n²) | O(1) |
| Using a set | O(n) average | O(n) |
Time complexity of common operations
| Operation | Time |
|---|---|
| Read an array item by index | O(1) |
| Search an unsorted array | O(n) |
| Binary search in a sorted array | O(log n) |
| Insert at the front of an array | O(n) |
| Insert at the head of a linked list | O(1) |
| Find the item at position i in a linked list | O(n) |
| Look up a key in a hash map | O(1) average |
| Bubble sort | O(n²) |
| Merge sort | O(n log n) |
The linked list rows are explained in what is a linked list.
How to find the Big O of your code
- Decide what n is (array length, string length, the number itself).
- Find the loops and recursive calls.
- Ask how many times each loop runs in terms of n.
- Multiply for nested loops, add for loops one after another.
- Drop constants and keep only the biggest term.
Try it on this code:
for (int i = 0; i < n; i++) {
System.out.println(i);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.println(i + j);
}
}
The first loop is n. The nested loops are n x n. Total n + n², which is O(n²).
Interview note: After you write a solution, say its time and space complexity before the interviewer asks. Start with "Let n be the length of the array." Then explain which loop decides the answer.
Quick revision
- Time complexity measures how steps grow with input size n.
- Big O keeps the biggest term and drops constants.
- One loop is O(n). Nested loops over the same data are O(n²). Halving each time is O(log n).
- Space complexity measures extra memory in the same way.
- You can often trade extra memory for less time.
Big O is used for every data structure and algorithm you will learn next. Continue with the data structures and algorithms guide, follow the plan in how to learn DSA from scratch, and test yourself with the DSA interview questions.
Frequently Asked Questions
What is time complexity in simple words?
What does O(n) mean?
Why do we drop constants in Big O?
What is the difference between time and space complexity?
Is O(log n) faster than O(n)?
Want to Build Your Career in Java Full Stack with AI?
Join CodeBegun and train with working industry engineers — Explore the Java Full Stack program

