Best, average and worst case
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Two arrays can have the exact same length n = 1,000,000, yet a search method finishes in 1 step on the first array and 1,000,000 steps on the second. To describe that difference, we separate best case, average case, and worst case.
Best and worst case of linear search
The worst case is the input that makes an algorithm take the longest. Interview answers usually give the worst-case time complexity.
Consider searching an unsorted array nums from left to right for a target value and returning as soon as you find it.
Example 1 · Best, average, and worst case of linear search
public class LinearSearchCasesDemo { public static int searchSteps(int[] nums, int target) { int steps = 0; for (int i = 0; i < nums.length; i++) { steps++; if (nums[i] == target) { return steps; } } return steps; }
public static void main(String[] args) { int[] data = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; System.out.println("Best case (first element) : " + searchSteps(data, 10) + " step"); System.out.println("Middle case (5th element) : " + searchSteps(data, 50) + " steps"); System.out.println("Worst case (not present) : " + searchSteps(data, 999) + " steps"); }}Best case (first element) : 1 step Middle case (5th element) : 5 steps Worst case (not present) : 10 steps
What this code does
- On the exact same 10-element array,
searchStepstakes1step in the best case (O(1)) and10steps in the worst case (O(n)). - Because we cannot promise
targetwill always sit at index0, the worst-case time complexity isO(n).
- Best case: The luckiest input of size
n(minimum steps, such as findingtargetat index0->O(1)). - Worst case: The hardest input of size
n(maximum steps, such astargetmissing ->O(n)). - Average case: The expected steps averaged over typical inputs of size
n(n / 2->O(n)).
In the best case, target sits right at index 0, so the loop checks 1 element and returns immediately (O(1)). In the worst case, target sits at the very last index n - 1—or is not in the array at all—so the loop checks all n elements (O(n)). In the average case (assuming target is equally likely to be at any index), it checks about n / 2 elements, which simplifies to O(n).
Why interviews ask for the worst case
When an interviewer asks 'What is the time complexity of your code?' without specifying a case, they almost always mean the worst case (or the average case alongside the worst case for hash tables).
Why? Because online judges deliberately include worst-case inputs in their hidden test suites, and production systems must guarantee they will not freeze when a user sends an unlucky or malicious request. A performance guarantee is only as strong as its worst case.
- If a loop can run
ntimes when no early exit triggers, its worst-case complexity isO(n). - For
HashSetandHashMap, state both: 'O(1)average time per lookup, andO(log n)worst case in Java 17 when many keys collide in one tree-backed bucket.'
break improves the best case, but if the worst-case input never triggers that break, the worst-case Big O stays the same.Amortised cost: ArrayList add (simplified)
How can ArrayList.add(x) be fast if its internal array eventually fills up and has to be copied into a bigger array? We explain this using amortized cost—the average cost per operation across a sequence of n operations, even when a single operation is occasionally expensive.
Example 2 · Simulating amortized O(1) cost when a dynamic array doubles
public class AmortizedDoublingSimulationDemo { // Simplified model: capacity starts at 1 and doubles whenever size == capacity public static void simulateAdds(int n) { int capacity = 1; int size = 0; long writeSteps = 0; long copySteps = 0;
for (int i = 0; i < n; i++) { if (size == capacity) { copySteps += size; // copy all existing elements into the new 2x array capacity *= 2; } size++; writeSteps++; // write the new element } long totalSteps = writeSteps + copySteps; System.out.println("n=" + n + " | writes=" + writeSteps + " | copies=" + copySteps + " | total=" + totalSteps + " (< 3n)"); }
public static void main(String[] args) { simulateAdds(16); simulateAdds(1024); }}n=16 | writes=16 | copies=15 | total=31 (< 3n) n=1024 | writes=1024 | copies=1023 | total=2047 (< 3n)
What this code does
- Across
1,024insertions, all array-doubling resizes combined copy only1 + 2 + 4 + ... + 512 = 1,023elements! - Total work for
ninsertions is2n - 1steps, which is less than2steps per insertion on average (O(1)amortized).
- Most
add(x)calls:1step (O(1)). - Rare resize call: copies
nelements (O(n)worst case for that single call). - Averaged over
nconsecutive adds:< 3steps per add (O(1)amortized). (Note: in Java 17's actualArrayList, capacity grows by roughly1.5x, which gives the exact sameO(1)amortized result.)
In a simplified model where an ArrayList starts at capacity 1 and doubles its array size whenever it fills up (1 -> 2 -> 4 -> 8 -> ... -> n), almost all add calls just write into the next free slot in 1 step. When a resize does happen at sizes 1, 2, 4, 8, ..., n, the total number of elements copied across all resizes combined is 1 + 2 + 4 + ... + n < 2n. Dividing < 3n total work across n adds gives less than 3 steps per add—O(1) amortized time per add!
Hidden costs in library calls: contains, substring, string +
The easiest way to accidentally write an O(n²) method in Java is to call an O(n) library method inside an O(n) loop. Because the library call looks like a single word, its internal loop is hidden from view.
Example 3 · Brute force: build a string with += in a loop (O(n²) time, O(n) space)
public class StringPlusLoopDemo { public static void main(String[] args) { int n = 1000; String s = ""; long copied = 0; for (int i = 0; i < n; i++) { s += 'a'; // builds a brand-new String each time copied += s.length(); // the new String's characters were all written } System.out.println("Built length " + s.length() + ", characters written " + copied); }}Built length 1000, characters written 500500
What this code does
- Because a String cannot change, each
s += 'a'creates a new String and writes every character again. - Adding 1,000 characters writes 1 + 2 + ... + 1,000 = 500,500 characters, which is O(n²).
Example 4 · Optimal: build the string with a StringBuilder (O(n) time, O(n) space)
public class StringBuilderLoopDemo { public static void main(String[] args) { int n = 1000; StringBuilder sb = new StringBuilder(); long written = 0; for (int i = 0; i < n; i++) { sb.append('a'); // writes only the new character written++; } System.out.println("Built length " + sb.length() + ", characters written " + written); }}Built length 1000, characters written 1000
What this code does
- The result is the same 1,000 characters, but each append writes only the new character.
- It is faster because a StringBuilder keeps a growable buffer and changes it in place, so the total work is O(n) instead of O(n²).
- Fix for
ArrayList.contains(x)inside a loop: use aHashSet(O(1)average lookup). - Fix for
s.substring(...)inside a loop: pass(s, left, right)indices or uses.charAt(i). - Fix for
result += ...inside a loop: useStringBuilder.append(...)(O(n)total time).
Watch three calls closely in Java 17: list.contains(x) (and list.indexOf(x) / list.remove(i)) on an ArrayList scans the list linearly in O(n) time; s.substring(a, b) in Java 7u6+ and Java 17 allocates and copies k = b - a characters in O(k) time and space; and result += ch on a String inside a loop copies the entire result string on every iteration (1 + 2 + ... + n = O(n^2) time)!
Find the bug
Find the hidden O(n²) cost
Tap the line that hides the extra loop.
This builds a report of n lines. Which line makes it O(n²)?
Round 1 of 3Next step
Check your understanding
10 quick questions