In this tutorial
Two programs can produce exactly the same output, yet one finishes in a blink and the other takes minutes once the data grows. Big O notation is how developers describe that difference. It also comes up in almost every technical interview, so it is worth understanding properly.
What Big O measures
Big O describes how the running time (or memory) of an algorithm grows as the input size n grows. It ignores constant factors and small details and focuses on the shape of the growth.
If an algorithm takes 3n + 10 steps, we say it is O(n): double the input and the time roughly doubles. The 3 and the 10 do not matter when n is a million.
Big O usually describes the worst case, unless stated otherwise.
The common complexities
O(1): constant time
The work does not depend on the input size.
int first(int[] a) {
return a[0];
}
Reading an array element by index, HashMap.get (on average) and pushing to an ArrayDeque are all O(1).
O(log n): logarithmic time
The problem is cut in half (or by some fraction) at each step. Doubling the input adds just one more step.
int halvings(int n) {
int steps = 0;
while (n > 1) {
n /= 2;
steps++;
}
return steps;
}
Binary search and lookups in a TreeMap are O(log n). For a billion items, log₂ n is only about 30.
O(n): linear time
You look at each element once.
int max(int[] a) {
int best = a[0];
for (int x : a) {
if (x > best) best = x;
}
return best;
}
ArrayList.contains, summing a list and most single loops over the input are O(n).
O(n log n): linearithmic time
Typical of efficient sorting algorithms such as merge sort and the algorithms behind Arrays.sort and Collections.sort. It is only slightly worse than linear in practice, and it is the best you can do for general comparison-based sorting.
O(n²): quadratic time
Usually a loop inside a loop over the same data.
boolean hasDuplicate(int[] a) {
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) return true;
}
}
return false;
}
For 1,000 items that is about half a million comparisons; for 1,000,000 items it is about 500 billion. Quadratic algorithms are fine for small inputs and painful for large ones.
O(2ⁿ) and O(n!): exponential and factorial
These appear in brute-force solutions that try every combination, such as naive recursive Fibonacci or checking every ordering of a list. They become unusable for even modest input sizes (n around 30 to 40 for 2ⁿ).
Seeing the difference
Approximate number of steps for different input sizes:
- n = 10: O(log n) ≈ 3, O(n) = 10, O(n log n) ≈ 33, O(n²) = 100
- n = 1,000: O(log n) ≈ 10, O(n) = 1,000, O(n log n) ≈ 10,000, O(n²) = 1,000,000
- n = 1,000,000: O(log n) ≈ 20, O(n) = 1,000,000, O(n log n) ≈ 20,000,000, O(n²) = 1,000,000,000,000
At a million items, the O(n²) algorithm does about fifty thousand times more work than the O(n log n) one.
Improving an algorithm: a worked example
The hasDuplicate method above is O(n²). Using a HashSet, whose add is O(1) on average, brings it down to O(n):
import java.util.HashSet;
import java.util.Set;
public class Duplicates {
static boolean hasDuplicateFast(int[] a) {
Set<Integer> seen = new HashSet<>();
for (int x : a) {
if (!seen.add(x)) { // add returns false if x was already present
return true;
}
}
return false;
}
public static void main(String[] args) {
System.out.println(hasDuplicateFast(new int[]{4, 8, 15, 16, 23, 42})); // false
System.out.println(hasDuplicateFast(new int[]{4, 8, 15, 8})); // true
}
}
We traded memory (the set uses O(n) extra space) for speed. That time-space trade-off is one of the most common moves in algorithm design, and interviewers love to hear you mention it.
Rules for working out Big O
- Drop constants: O(2n) is O(n).
- Drop smaller terms: O(n² + n) is O(n²).
- Sequential steps add: a loop over
afollowed by a loop overbis O(a + b). - Nested steps multiply: a loop over
acontaining a loop overbis O(a × b). - Different inputs get different letters. Do not call it O(n²) if the two loops run over different arrays.
- Watch hidden loops. Calling
list.contains(x)inside a loop over the list is O(n²), even though you only wrote one loop.
Complexity of everyday Java collections
- ArrayList:
get/setO(1);addat end O(1) amortised;add/removeat index O(n);containsO(n). - LinkedList: add/remove at the ends O(1);
get(i)O(n). - HashMap / HashSet:
put,get,contains,removeO(1) on average, O(log n) worst case since Java 8. - TreeMap / TreeSet:
put,get,contains,removeO(log n), and keys are kept sorted. - ArrayDeque: push, pop, offer, poll at either end O(1).
- PriorityQueue:
offerandpollO(log n);peekO(1). - Arrays.sort / Collections.sort: O(n log n).
Knowing this list lets you spot slow code quickly. If you see list.contains inside a loop, ask whether a HashSet would turn O(n²) into O(n).
Space complexity
Big O applies to memory too. The hasDuplicateFast method uses O(n) extra space; the nested-loop version uses O(1). Recursive methods use stack space proportional to their depth: a recursion that goes n levels deep uses O(n) stack, and can throw StackOverflowError if n is large.
How to talk about Big O in interviews
- State the complexity of your first idea, even if it is brute force: “This is O(n²) time and O(1) space.”
- Then improve it: “Using a HashSet, we can get O(n) time at the cost of O(n) space.”
- Mention the best, average and worst case when they differ (for example, quicksort is O(n log n) on average but O(n²) in the worst case).
Summary
- Big O describes how cost grows with input size, ignoring constants.
- From best to worst: O(1), O(log n), O(n), O(n log n), O(n²), O(2ⁿ).
- Nested loops multiply, sequential steps add, and library calls can hide loops.
- Choosing the right collection is often the easiest way to improve complexity.