The cost table: why the structure matters more than the code
A data structure is a decision about which operations are cheap. ArrayList.get(i) is instant; ArrayList.contains(x) checks every element. HashSet.contains(x) is instant but the set has no order. Picking the structure is usually the whole performance story: the same loop over the wrong structure can be a thousand times slower, and no amount of clever code inside the loop fixes that.
The notation is Big-O: how the work grows as the input size n grows. O(1) means "the same cost no matter how big", O(log n) means "one more step each time n doubles", O(n) means "proportional to n", O(n log n) is what good sorting costs, O(n²) is a loop inside a loop.
| Structure (java.util) | Get by index / key | Search | Insert | Remove |
|---|---|---|---|---|
array / ArrayList | O(1) | O(n) | O(1) amortised at end, O(n) in middle | O(1) at end, O(n) in middle |
LinkedList | O(n) | O(n) | O(1) at either end | O(1) at either end |
ArrayDeque (stack / queue) | ends only | O(n) | O(1) at either end | O(1) at either end |
HashMap / HashSet | O(1) average | O(1) average by key | O(1) average | O(1) average |
TreeMap / TreeSet (red-black tree) | O(log n) | O(log n) | O(log n) | O(log n) |
PriorityQueue (binary heap) | O(1) peek at min | O(n) | O(log n) | O(log n) poll |
| Graph (adjacency list) | - | O(V + E) with BFS / DFS | O(1) add edge | O(degree) remove edge |
public class Main {
public static void main(String[] args) {
int n = 1_000_000;
int[] sorted = new int[n];
for (int i = 0; i < n; i++) sorted[i] = i * 2;
int target = 1_999_998;
int linearSteps = 0;
for (int x : sorted) {
linearSteps++;
if (x == target) break;
}
int binarySteps = 0, lo = 0, hi = n - 1;
while (lo <= hi) {
binarySteps++;
int mid = (lo + hi) >>> 1;
if (sorted[mid] == target) break;
if (sorted[mid] < target) lo = mid + 1; else hi = mid - 1;
}
System.out.println("linear search steps: " + linearSteps);
System.out.println("binary search steps: " + binarySteps);
}
}linear search steps: 1000000
binary search steps: 20O(n) versus O(log n) on a million sorted items: one checks every element, the other halves the range each step. 2 to the 20th is about a million, so 20 steps.
Change n to 2,000,000 and predict both numbers before running it. The linear count doubles; the binary count goes up by exactly one.
java.util class you would actually use at work. In an interview you may be asked to build either one, so learn both.