Skip to lesson

Best, average and worst case

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

LinearSearchCasesDemo.javaJava
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");    }}
Output
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, searchSteps takes 1 step in the best case (O(1)) and 10 steps in the worst case (O(n)).
  • Because we cannot promise target will always sit at index 0, the worst-case time complexity is O(n).
  • Best case: The luckiest input of size n (minimum steps, such as finding target at index 0 -> O(1)).
  • Worst case: The hardest input of size n (maximum steps, such as target missing -> 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 n times when no early exit triggers, its worst-case complexity is O(n).
  • For HashSet and HashMap, state both: 'O(1) average time per lookup, and O(log n) worst case in Java 17 when many keys collide in one tree-backed bucket.'
Adding an early 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

AmortizedDoublingSimulationDemo.javaJava
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);    }}
Output
n=16 | writes=16 | copies=15 | total=31 (< 3n)
n=1024 | writes=1024 | copies=1023 | total=2047 (< 3n)

What this code does

  • Across 1,024 insertions, all array-doubling resizes combined copy only 1 + 2 + 4 + ... + 512 = 1,023 elements!
  • Total work for n insertions is 2n - 1 steps, which is less than 2 steps per insertion on average (O(1) amortized).
  • Most add(x) calls: 1 step (O(1)).
  • Rare resize call: copies n elements (O(n) worst case for that single call).
  • Averaged over n consecutive adds: < 3 steps per add (O(1) amortized). (Note: in Java 17's actual ArrayList, capacity grows by roughly 1.5x, which gives the exact same O(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)

StringPlusLoopDemo.javaJava
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);    }}
Output
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)

StringBuilderLoopDemo.javaJava
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);    }}
Output
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 a HashSet (O(1) average lookup).
  • Fix for s.substring(...) inside a loop: pass (s, left, right) indices or use s.charAt(i).
  • Fix for result += ... inside a loop: use StringBuilder.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 3

Next step

Check your understanding

10 quick questions