BackendBench
Coffee
Spot the Bug #107

The slow report

A medium Java puzzle in the string handling family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

mediumString handlingbuggy line: 7

Highlighted: line 7. Play this one as a puzzle without the answer.

What is wrong

Each += creates a new String and copies everything built so far, so the time is quadratic. With 200,000 rows the method takes minutes and creates huge garbage. It is fast for small test inputs.

The fix

StringBuilder sb = new StringBuilder(); for (String row : rows) sb.append(row).append('\n'); return sb.toString();

How to avoid it next time

Use StringBuilder or String.join/Collectors.joining for repeated concatenation in loops.

Want the background? Read StringBuilder and string building in the Java concepts library.

About string handling

Strings are immutable, split and replaceAll take regular expressions, and character encodings default to whatever the platform says. Small misunderstandings produce wrong output rather than errors.

In code review: Look at whether the return value of a String method is used, whether a pattern argument is a regex, and whether an encoding is named explicitly.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #106#108 โ†’

Frequently asked questions

What is the bug in "The slow report"?

Each += creates a new String and copies everything built so far, so the time is quadratic. With 200,000 rows the method takes minutes and creates huge garbage. It is fast for small test inputs. The faulty line is line 7: result += row + "\n";

How do I fix it?

Replace it with: StringBuilder sb = new StringBuilder(); for (String row : rows) sb.append(row).append('\n'); return sb.toString();. Use StringBuilder or String.join/Collectors.joining for repeated concatenation in loops.

How do I catch string handling in code review?

Look at whether the return value of a String method is used, whether a pattern argument is a regex, and whether an encoding is named explicitly.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need