Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A report generator is very slow. The code is:

Java
for (int i = 0; i < list.size(); i++) {
process(list.get(i));
}

where list is a LinkedList of 200,000 items. Explain the complexity and fix.

Each list.get(i) on a LinkedList walks node by node from the nearer end, so the loop does about n squared over 4 node hops in total, about 10 billion for 200,000 items. The fix is to iterate with a for-each loop or an Iterator, which moves one link per step and makes the loop O(n), or to copy into an ArrayList when the code really needs random access. API code that accepts any List should not assume get(i) is cheap unless the list implements RandomAccess.

Why this question is asked

This is a classic performance bug because the code looks perfectly reasonable: an index loop over a list. It only becomes slow when someone, often far away in another module, passes a LinkedList. Interviewers like it because it tests whether we can connect an innocent-looking line to an algorithmic cost, prove it, and fix it at the right level. In this answer, we will reproduce the slowdown, count exactly how much work the loop does, fix it two ways, and then look at how to write APIs that do not fall into the trap.

1Reproducing the Slowdown

Let us run the same loop over an ArrayList and a LinkedList of 200,000 items. The process() method does almost nothing, so the time we measure is the cost of reaching each element.

Java
List<Integer> array = new ArrayList<>();
List<Integer> linked = new LinkedList<>();
for (int i = 0; i < 200_000; i++) { array.add(i); linked.add(i); }
long sum = 0, t0 = System.nanoTime();
for (int i = 0; i < array.size(); i++) sum += array.get(i);
System.out.println((System.nanoTime() - t0) / 1_000_000 + " ms"); // about 1 ms
t0 = System.nanoTime();
for (int i = 0; i < linked.size(); i++) sum += linked.get(i);
System.out.println((System.nanoTime() - t0) / 1_000_000 + " ms"); // several seconds or more

The exact numbers depend on the machine, but the gap is thousands of times, not a few percent. A quick measurement like this is not a proper benchmark, which would use JMH, but a gap this size does not need precision to be convincing.

2Why the Loop Is O(n squared)

A LinkedList has no array. To return element i, get(i) starts at the first node if i is in the first half, or at the last node otherwise, and follows i links (or size minus i links). So reaching position i costs up to n/2 hops, and the loop asks for every position in turn.

Adding it up: for indexes near the ends the walk is short, and for indexes near the middle it is about n/2. On average a get walks about n/4 nodes, so the loop does n times n/4 hops in total. For n = 200,000 that is 200,000 times 50,000, about 10 billion pointer hops, each one a potential cache miss. That is O(n squared): doubling the report size makes it four times slower.

Notice that list.size() in the loop condition is not the problem. LinkedList keeps a size field, so size() is O(1). The cost is entirely in get(i).

Work done by the index loop on a LinkedList
Items nAverage hops per getTotal hops
1,000250250 thousand
20,0005,000100 million
200,00050,00010 billion
400,000100,00040 billion
Ten times more items cost a hundred times more work.

3Fix 1: Iterate Instead of Indexing

The for-each loop uses the list's Iterator. A LinkedList iterator remembers the node it is standing on, so next() follows one link and returns the item. Each element is reached in one hop, and the whole loop is O(n) whatever the list implementation.

Java
for (Integer item : list) { // uses list.iterator() behind the scenes
process(item); // 200,000 hops in total, about a millisecond
}
// If we also need the index, keep a counter or use a ListIterator
ListIterator<Integer> it = list.listIterator();
while (it.hasNext()) {
int index = it.nextIndex(); // 0, 1, 2, ...
process(index, it.next());
}

This is the fix we would apply first, because it is correct for every kind of list and reads better than the index loop. A stream, list.forEach(this::process) or list.stream(), also iterates and is O(n).

4Fix 2: Copy to an ArrayList for Random Access

Sometimes the code really needs random access, for example comparing element i with element i + 7, or jumping around during a binary search. Then we copy once into an ArrayList, which costs O(n), and every get afterwards is O(1).

Java
List<Integer> rows = new ArrayList<>(linked); // one O(n) copy
for (int i = 0; i + 7 < rows.size(); i++) {
compare(rows.get(i), rows.get(i + 7)); // O(1) each
}

Better still, we ask why the data is a LinkedList at all. If it is built by appending and then read, an ArrayList is the better structure from the start, and changing the producer fixes every consumer.

5Writing APIs That Do Not Assume Cheap get

The deeper lesson is about API contracts. A method that accepts List<T> can receive any list, so it should not assume get(i) is cheap. The JDK provides a marker for this: the RandomAccess interface, which has no methods and is implemented by lists with fast indexed access, such as ArrayList, but not by LinkedList. JDK algorithms such as Collections.binarySearch check it to choose between indexing and iterating.

Java
static <T> void processAll(List<T> list, Consumer<? super T> action) {
if (list instanceof RandomAccess) {
for (int i = 0, n = list.size(); i < n; i++) action.accept(list.get(i));
} else {
for (T t : list) action.accept(t); // safe for LinkedList
}
}
Step throughChoosing how to loop over a List we received
  1. Do we need the index or random jumps?
    YesIs it RandomAccess?NoUse for-each or a stream
  2. Is it RandomAccess?
    YesIndex loop is fineNoCopy to ArrayList once
  3. Process the elementsO(n) in every case

3 steps in order. Play them, or step through them one at a time.

In most code we do not need even this branch: a for-each loop is fast on both kinds of list. The check matters in libraries and hot paths where the index loop has a real advantage on arrays. Either way, the rule is simple: index loops are fine for lists we created ourselves as ArrayList, and suspicious on any List we received from someone else.

6Follow-up questions

Would caching list.size() in a variable have helped?

No. LinkedList.size() is already O(1), because the list keeps a counter. The cost is in get(i), which walks the nodes every time, so moving size() out of the loop changes nothing measurable.

How would we find this in production?

A CPU profile with a sampling profiler such as async-profiler or Java Flight Recorder shows most samples inside LinkedList.node(), the internal method that walks to an index, called from our report loop. That points straight at the get(i) calls, and the stack shows which caller passed the LinkedList.

Is the for-each loop slower than the index loop on an ArrayList?

Not in any way that matters. The JIT compiler optimises both well, and the difference is usually within measurement noise. We choose for-each for clarity and safety, and use index loops only where we need the index or have measured a gain.

7Conclusion

In this answer, we saw that get(i) on a LinkedList walks from the nearer end, so an index loop over 200,000 items does about 10 billion node hops and is O(n squared). Iterating with for-each or an Iterator makes it O(n), copying to an ArrayList gives cheap random access when we truly need it, and API code should only rely on fast get(i) for lists that implement RandomAccess.

What to say in the interviewAbout 90 seconds aloud

Open with

The loop is quadratic. A LinkedList has no array behind it, so get of i walks node by node from whichever end is nearer. The loop calls get for every index, so on average each call walks about a quarter of the list, and for 200,000 items that is roughly 200,000 times 50,000, around ten billion pointer hops, each potentially a cache miss.

Then, if they want more

Doubling the data makes it four times slower. size is not the problem, because LinkedList stores its size, so it is O(1). The first fix is to iterate instead of indexing: a for-each loop uses the iterator, which remembers the current node, so each step is one hop and the loop is linear for any list.

If I need the index too, I keep a counter or use a ListIterator and nextIndex. If the code really needs random access, like comparing elements several positions apart, I copy once into an ArrayList, which is O(n), and then get is constant time.

I would also ask why it is a LinkedList at all, because for build-then-read data an ArrayList is better from the start. The broader point is that a method accepting a List should not assume get is cheap. Lists with fast indexing implement the RandomAccess marker interface, and JDK algorithms check it. To confirm in production, a profile would show the time inside LinkedList.node.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A report generator is very slow. The code is:": https://scrivio-interview-library.netlify.app/java/lists/fceec4e50e/