Time complexity
Time complexity describes how the amount of work an algorithm does grows as its input grows. It is a shape, not a stopwatch reading.
Detailed Explanation
You have written a method that works on ten records. The question that matters in production is whether it still works on ten million. Time complexity is the tool for answering that before you ship.
Measuring with System.nanoTime() answers a narrower question. A timing number describes one machine, one JIT warmup state, one set of test data. Move the code to a slower server and the number changes. Time complexity ignores the machine and counts how the number of operations grows with the input size, usually called n.
Big-O notation writes that growth down. It keeps the dominant term and throws away constants. An algorithm doing 3n + 7 steps is O(n), because once n is large the +7 and the 3 stop mattering next to n itself. That is the rule. The exception matters too: constants are invisible in the notation but very visible in your latency graphs, so O(n) with a database call per element is worse than O(n log n) in memory.
These are the classes you will meet most:
| Notation | Name | Typical source |
|---|---|---|
O(1) | constant | HashMap.get, array indexing |
O(log n) | logarithmic | binary search, TreeMap.get |
O(n) | linear | one pass over a list |
O(n log n) | linearithmic | Collections.sort, Arrays.sort |
O(n^2) | quadratic | a loop nested inside a loop over the same data |
O(2^n) | exponential | naive recursion over subsets |
To read complexity out of Java code, look at two things. First, the nesting of your own loops: two loops over the same n give O(n^2). Second, what the library calls cost, because those are loops you did not write. list.contains(x) on an ArrayList is O(n), so calling it inside a loop is quadratic even though your code shows one loop. set.contains(x) on a HashSet is O(1) on average, and swapping one for the other is the single most common fix for slow interview code.
Two refinements come up constantly. Average versus worst case: HashMap.get is O(1) on average but O(log n) in the worst case, because since Java 8 a bucket with many colliding keys becomes a red-black tree instead of a linked list. Amortized cost: ArrayList.add is O(1) amortized. Most calls are constant time, and the occasional call that doubles the backing array and copies everything is O(n), but spread across all the adds the average stays constant.
You reach for complexity analysis when choosing a data structure, when explaining why a report that was fine in staging times out in production, and in every technical interview you will ever sit.
What it costs you: precision. Big-O hides constant factors, memory traffic, and cache behaviour. An int[] scan beats a LinkedList<Integer> scan by a wide margin at the same O(n), because the array is contiguous and needs no pointer chasing or unboxing.
Code Examples
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class DuplicateCheck {
// O(n^2): for every element, scan the rest of the list again.
static boolean hasDuplicateQuadratic(List<String> items) {
for (int i = 0; i < items.size(); i++) {
for (int j = i + 1; j < items.size(); j++) {
if (items.get(i).equals(items.get(j))) {
return true;
}
}
}
return false;
}
// O(n): one pass, and each set operation is O(1) on average.
static boolean hasDuplicateLinear(List<String> items) {
Set<String> seen = new HashSet<>();
for (String item : items) {
// add returns false when the element was already in the set
if (!seen.add(item)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
var emails = List.of("a@x.com", "b@x.com", "a@x.com");
System.out.println(hasDuplicateQuadratic(emails)); // prints: true
System.out.println(hasDuplicateLinear(emails)); // prints: true
}
}import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class IndexingCost {
static long sumByIndex(List<Integer> list) {
long total = 0;
// get(i) is O(1) on ArrayList but O(i) on LinkedList, which walks the chain.
for (int i = 0; i < list.size(); i++) {
total += list.get(i); // unboxing Integer to int happens here
}
return total;
}
public static void main(String[] args) {
List<Integer> arrayList = new ArrayList<>();
List<Integer> linkedList = new LinkedList<>();
for (int i = 0; i < 50_000; i++) {
arrayList.add(i);
linkedList.add(i);
}
// Identical loop, identical answer, but the LinkedList version is O(n^2).
System.out.println(sumByIndex(arrayList)); // prints: 1249975000
System.out.println(sumByIndex(linkedList)); // prints: 1249975000
}
}Common Gotchas
Big-O hides the constant factor
`O(n log n)` is not always faster than `O(n^2)` on small inputs. `Arrays.sort` on primitives switches to insertion sort for tiny ranges for exactly this reason. Complexity tells you how something scales, not which of two candidates wins at `n = 20`.
Library calls hide loops
`List.contains`, `List.remove(Object)`, `List.indexOf` and `String.concat` inside a loop each turn linear code quadratic. Read the Javadoc for the cost before you put a collection method inside a loop.
Benchmarking on a cold JVM measures the interpreter
the first few thousand iterations run before the JIT compiles the method, so a quick timing harness can rank two algorithms backwards. Use JMH, or discard several warmup rounds, before trusting a measured number.