Big-O for
Collections
Understand how time complexity affects loops and common Java collection operations: from ArrayList to HashMap.
What Is Big-O Notation?
Big-O notation describes the upper bound of how an algorithm's running time grows relative to the input size \( n \). It answers: "As my data gets bigger, how much slower does my code get?"
Visualizing Growth Rates
Why Big-O Matters in Java
Java gives you many collection classes, but they have different performance characteristics. Picking the wrong one can turn a snappy app into a crawling one.
The Core Rule: Counting Loop Iterations
The simplest way to find Big-O: count how many times the innermost operation runs as a function of input size \( n \).
Loop Patterns at a Glance
ArrayList vs LinkedList
| Operation | ArrayList | LinkedList |
|---|---|---|
| get(index) | \( O(1) \) | \( O(n) \) |
| add(end) | \( O(1) \) amortized | \( O(1) \) |
| add(index, elem) | \( O(n) \) | \( O(n) \) |
| remove(index) | \( O(n) \) | \( O(n) \) |
| contains(obj) | \( O(n) \) | \( O(n) \) |
HashMap & HashSet Power
Hash-based structures use a hash function to compute an index in an internal array, giving near-instant access.
TreeMap & TreeSet: Sorted Order
Tree-based collections keep elements in sorted order using a Red-Black tree. Every operation walks the tree height, which is \( O(\log n) \).
How to Analyze Your Code
Example 1: Simple Loop
Example 2: Hidden \( O(n^2) \)
Example 3: Sort Then Search
Common Mistakes
The Big-O Cheat Sheet
| Collection | Access | Search | Insert | Delete |
|---|---|---|---|---|
| ArrayList | \( O(1) \) | \( O(n) \) | \( O(1) \)* | \( O(n) \) |
| LinkedList | \( O(n) \) | \( O(n) \) | \( O(1) \)* | \( O(n) \) |
| HashMap | \( O(1) \) | \( O(1) \) | \( O(1) \) | \( O(1) \) |
| TreeMap | \( O(\log n) \) | \( O(\log n) \) | \( O(\log n) \) | \( O(\log n) \) |
| HashSet | — | \( O(1) \) | \( O(1) \) | \( O(1) \) |
Question 1 of 5
What is the time complexity of calling get(i) on an ArrayList in Java?
Question 2 of 5
You have a loop that iterates through an ArrayList of size \( n \), and inside the loop you call list.contains(item). What is the total time complexity?
Question 3 of 5
Which Java collection provides \( O(1) \) average time for both insertion and membership testing?
Question 4 of 5
Consider the following code:
Collections.sort(data); // Step 1
for (String q : queries) { // Step 2
int i = Collections.binarySearch(data, q);
}
Assume data has \( n \) elements and queries has \( n \) elements.
What is the overall time complexity of this code?
Question 5 of 5
A developer replaces an ArrayList with a HashSet inside a loop to check for duplicates. The overall complexity drops from \( O(n^2) \) to \( O(n) \). Why?