Build strings efficiently in each language and avoid quadratic concatenation.
Use it when the answer is a long text made from many pieces or from a scan of another text. Signal words: build a long string, join the pieces, a report as text, string in a loop.
Start an empty builder: a list in Python and JavaScript, a StringBuilder in Java, an empty std::string in C++.
Step write the next piece, or the next kept character, at the end of the builder. Put a separator before a piece, never after the last one.
Stop when all pieces or characters are done. Make the string once.
It does not need a builder when the text is short or built once from two or three parts. Clear code is better there.
Cost: O(n) time for a total length of n, and O(n) extra space for the builder.
In this lesson you build long strings without copying the same text again and again. You learn what a string costs in each language, what a builder is, and why slices and lengths need care.
You work on the nightly export of an online store. It receives order codes in the order they were placed, and it writes one text report with one code on each line. The newest code must come first.
A code has 10 characters, for example ORD-000123. A busy night has 100,000 codes, so the report holds about a million characters.
Your team lead says: The export must finish in a few seconds. Build the report as one text, newest code first.
Here is a short test: the codes A12, B7, C30 and D4 arrive in that order. The report reads D4, C30, B7 and A12, with a separator between them.
A clerk has a pile of paper strips, one for each code. To make one long strip, the clerk could tape each new code to the front of the long strip. Each time, the clerk must copy the whole long strip onto a fresh piece of paper first, because a printed strip cannot be changed.
Or the clerk could lay all the codes on a table in order, and copy them onto one fresh strip once. The long strip is the string, and the table is the builder.
Like a clerk with paper strips: taping each code to the front copies the whole long strip every time, while laying them out and copying once does not.
Before you write the slow loop, build the report for four codes by hand. Keep a builder, add each piece once, and put the separator in the right places.
Solve it by hand: Four order codes joined with a separator. The hand-solve sheet loads in your browser.
The builder is the text so far. Each step adds a separator, then a piece, and nothing already in the builder is copied again.
The pieces are D4, C30, B7 and A12, newest first, and the separator is |.
| Place | Piece | Separator first? | Builder after |
|---|---|---|---|
| 0 | D4 | no, it is the first piece | D4 |
| 1 | C30 | yes | D4|C30 |
| 2 | B7 | yes | D4|C30|B7 |
| 3 | A12 | yes | D4|C30|B7|A12 |
The builder holds the finished report. Each character was written once.
Start with a correct version. It puts each new code in front of the report so far, so the newest code ends up first.
def build_report_first(codes):
report = ""
for code in codes: # oldest code first
report = code + "|" + report # a new string every time
return report[:-1] # cut the last separatorThis is correct. For the four test codes it makes D4|C30|B7|A12, and it is instant.
Now check the real size.
A busy night has 100,000 codes of 10 characters. A report line is 11 characters with its separator.
Here is the count from running the code:
The next table comes from running the same loop in each language. Each time is the best of three runs on one busy laptop. Times change with the load, so only the growth matters.
| Codes | Python | Java | C++ | JavaScript |
|---|---|---|---|---|
| 10,000 | 15 ms | 21 ms | 11 ms | under 1 ms |
| 20,000 | 45 ms | 63 ms | 41 ms | under 1 ms |
| 40,000 | 140 ms | 237 ms | 146 ms | under 1 ms |
| 80,000 | 519 ms | 1,281 ms | 535 ms | 1 ms |
Doubling the codes makes the time about three to four times as long in Python, Java and C++, close to the four times the copy count predicts. At 80,000 codes Java needs 1.3 seconds, and the real night has 100,000.
The loop puts each code in front, and that matters. In the same runs, appending with report += code + "|" took 4 ms in Python at 80,000 codes. CPython can grow a string in place when no other name refers to it, but other Python implementations need not.
Java took 1,239 ms for the appending loop too. The compiler turns each + line into one builder call, but every step still makes a new String. JavaScript took about 1 ms either way, for a reason explained later in this lesson.
Predict the cost
Q Each step copies the whole report so far. How does the number of characters copied grow when the number of codes doubles?
Answer: B
The copies add up to about 11 * n * n / 2. Doubling n multiplies that by about 4, which is what the table shows.
The first attempt is correct, but it copies the same text again and again. Now look at what the finished report needs.
Look at the hand trace again. The builder never copied what it already held. It only added at its end.
So collect the pieces in a builder. Add each piece once, with the separator before it, and turn the builder into one string at the very end. The key fact is that a builder can grow at its end without copying the old text each time. When it runs out of room, it grows by a fixed factor, so the copying stays proportional to the length.
Here is the same night, counted both ways:
| Method | Characters copied or written |
|---|---|
| Put each code in front of the report | 54,999,450,000 |
| Builder, made once at the end | 1,100,000 |
That is about 50,000 times fewer. In the runs above, the builder took under 3 milliseconds at 80,000 codes in every language.
Race: Building a report: one concatenation at a time against a builder. The operation counter loads in your browser.
At 1,000 codes the first attempt copies 5,494,500 characters and the builder writes 11,000. At 10,000 codes the counts are 549,945,000 against 110,000.
A builder adds each piece at its end without copying what it holds, and the string is made once, so each character is written once.
A second job cleans a text that has extra spaces. A run of spaces becomes one space, and spaces at the start and the end are removed. The text is ab c and the player shows a space as an underscore. It stops at five steps and asks how many characters the builder has written.
Dry run: Predict each step: clean the spaces. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row.
| Place | Character | Action | Builder holds |
|---|---|---|---|
| 2 | a | write | a |
| 3 | b | write | ab |
| 4 | space | write one space | ab |
| 5 | space | skip: a space was just written | ab |
| 6 | space | skip | ab |
| 7 | c | write | ab c |
| 8 | space | write one space | ab c |
The spaces at places 0 and 1 were skipped too. At the end the trailing space is cut, so the answer is ab c, with 4 characters.
A builder is a growing array: of characters in Java and C++, of the pieces in Python and JavaScript. Adding a piece costs at most the length of the piece. Making the string at the end copies every character once. So the whole job costs the total length of the answer, and it is O(n).
Exercise · Predict the output: Pieces that are empty. A report has two empty lines among its codes. What does this print, with the quote marks included?
pieces = ["", "A12", "", "B7"]
parts = []
for i, piece in enumerate(pieces):
if i > 0:
parts.append("-")
parts.append(piece)
print('"' + "".join(parts) + '"')Here is the rule that keeps a string build fast and correct. Every line of both templates exists to protect it.
The builder holds the answer so far, in order. Each character is written to it once, and the finished string is made once, at the end.
At the start the builder is empty. Each step writes the next characters of the answer at the end of the builder. Nothing already written is read again or copied, until the end.
When the loop ends, the builder holds the whole answer. One final step turns it into a string.
Use it when the answer is a long text made from many pieces or from a scan of another text. Signal words: build a long string, join the pieces, a report as text, string in a loop.
Start: an empty builder: a list in Python and JavaScript, a StringBuilder in Java, an empty std::string in C++.
Step: write the next piece, or the next kept character, at the end of the builder. Put a separator before a piece, never after the last one.
Stop: when all pieces or characters are done. Make the string once.
It does not need a builder when the text is short or built once from two or three parts. Clear code is better there.
Cost: O(n) time for a total length of n, and O(n) extra space for the builder.
def join_pieces(pieces, separator):
# [1] Make an empty builder: a list of parts, because a string would be copied at every step.
parts = []
# [2] Visit every piece once, in order.
for i, piece in enumerate(pieces):
# [3] Put the separator before every piece except the first.
if i > 0:
parts.append(separator)
# [4] Append the piece to the builder.
parts.append(piece)
# [5] Turn the builder into one string, once.
return "".join(parts)public String joinPieces(String[] pieces, String separator) {
// [1] Make an empty builder: a list of parts, because a string would be copied at every step.
StringBuilder parts = new StringBuilder();
// [2] Visit every piece once, in order.
for (int i = 0; i < pieces.length; i++) {
// [3] Put the separator before every piece except the first.
if (i > 0) {
parts.append(separator);
}
// [4] Append the piece to the builder.
parts.append(pieces[i]);
}
// [5] Turn the builder into one string, once.
return parts.toString();
}string joinPieces(vector<string>& pieces, string separator) {
// [1] Make an empty builder: a list of parts, because a string would be copied at every step.
string parts;
// [2] Visit every piece once, in order.
for (int i = 0; i < (int)pieces.size(); i++) {
// [3] Put the separator before every piece except the first.
if (i > 0) {
parts += separator;
}
// [4] Append the piece to the builder.
parts += pieces[i];
}
// [5] Turn the builder into one string, once.
return parts;
}function joinPieces(pieces, separator) {
// [1] Make an empty builder: a list of parts, because a string would be copied at every step.
const parts = [];
// [2] Visit every piece once, in order.
for (let i = 0; i < pieces.length; i++) {
// [3] Put the separator before every piece except the first.
if (i > 0) {
parts.push(separator);
}
// [4] Append the piece to the builder.
parts.push(pieces[i]);
}
// [5] Turn the builder into one string, once.
return parts.join("");
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Put it in order: One report from many codes. Arrange the lines into a function that joins the pieces with a separator between them, building the string once at the end.
def join_pieces(pieces, separator):
parts = []
for i, piece in enumerate(pieces):
if i > 0:
parts.append(separator)
parts.append(piece)
return "".join(parts)
parts.append(separator)
return partsdef collapse_spaces(text):
# [1] Make an empty builder, and treat the start as if a space was just written.
out = []
last_was_space = True
# [2] Visit every character once.
for ch in text:
if ch == " ":
# [3] Write a space only after a character that is not a space.
if not last_was_space:
out.append(" ")
last_was_space = True
else:
# [4] Any other character is written as it is.
out.append(ch)
last_was_space = False
# [5] Remove one trailing space, then build the string once.
if out and out[-1] == " ":
out.pop()
return "".join(out)public String collapseSpaces(String text) {
// [1] Make an empty builder, and treat the start as if a space was just written.
StringBuilder out = new StringBuilder();
boolean lastWasSpace = true;
// [2] Visit every character once.
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (ch == ' ') {
// [3] Write a space only after a character that is not a space.
if (!lastWasSpace) {
out.append(' ');
lastWasSpace = true;
}
} else {
// [4] Any other character is written as it is.
out.append(ch);
lastWasSpace = false;
}
}
// [5] Remove one trailing space, then build the string once.
if (out.length() > 0 && out.charAt(out.length() - 1) == ' ') {
out.setLength(out.length() - 1);
}
return out.toString();
}string collapseSpaces(string text) {
// [1] Make an empty builder, and treat the start as if a space was just written.
string out;
bool lastWasSpace = true;
// [2] Visit every character once.
for (char ch : text) {
if (ch == ' ') {
// [3] Write a space only after a character that is not a space.
if (!lastWasSpace) {
out += ' ';
lastWasSpace = true;
}
} else {
// [4] Any other character is written as it is.
out += ch;
lastWasSpace = false;
}
}
// [5] Remove one trailing space, then build the string once.
if (!out.empty() && out.back() == ' ') {
out.pop_back();
}
return out;
}function collapseSpaces(text) {
// [1] Make an empty builder, and treat the start as if a space was just written.
const out = [];
let lastWasSpace = true;
// [2] Visit every character once.
for (const ch of text) {
if (ch === " ") {
// [3] Write a space only after a character that is not a space.
if (!lastWasSpace) {
out.push(" ");
lastWasSpace = true;
}
} else {
// [4] Any other character is written as it is.
out.push(ch);
lastWasSpace = false;
}
}
// [5] Remove one trailing space, then build the string once.
if (out.length > 0 && out[out.length - 1] === " ") {
out.pop();
}
return out.join("");
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Find the bug: The space that stays at the start. This space cleaner should remove spaces at the start of the text, but it keeps one. Which line is wrong?
def collapse_spaces(text):
out = []
last_was_space = False
for ch in text:
if ch == " ":
if not last_was_space:
out.append(" ")
last_was_space = True
else:
out.append(ch)
last_was_space = False
if out and out[-1] == " ":
out.pop()
return "".join(out)To clean a text, scan it once and write the kept characters into a builder, then make the string at the end.
Exercise · Break it: The space at the end. This space cleaner skips leading spaces and shrinks each run of spaces to one, but it never removes the last space. Find a text where it gives the wrong answer.
def collapse_spaces(text):
out = []
last_was_space = True
for ch in text:
if ch == " ":
if not last_was_space:
out.append(" ")
last_was_space = True
else:
out.append(ch)
last_was_space = False
return "".join(out)| Language | Can a string change? | The builder | The trap |
|---|---|---|---|
| Python | No | A list of parts, then "".join(parts) |
s = t + s in a loop copies at every step. CPython can grow s += t in place when nothing else refers to s, but that is not a language promise |
| Java | No | StringBuilder |
s += t in a loop makes a new String each time. The compiler's own builder covers one line, not the loop |
| C++ | Yes | std::string with +=, and reserve when the size is known |
s = s + t and s = t + s make a temporary copy |
| JavaScript | No | An array of parts, then join("") |
Engines such as V8 often hide the cost of += with a tree of pieces, but that is an optimisation and not a promise |
The two templates answer two kinds of question. You can pick before you write any code.
Then check the ends: what do the templates do with no pieces, with empty pieces, and with an empty text?
| Situation | Method | Why |
|---|---|---|
| Report, log or file from many lines | Builder and join | Each character is written once |
| Clean or filter a text | Scan with a builder | One pass, one string at the end |
| Take pieces from the front of a text | Indexes | A slice copies its characters |
| Add two digit strings | A builder of digits, reversed once | No insertion at the front |
A store export writes one line for a product: the code SKU9, the name mug and the count 12, with a comma between the fields.
Use the join template.
| Place | Piece | Builder after |
|---|---|---|
| 0 | SKU9 | SKU9 |
| 1 | mug | SKU9,mug |
| 2 | 12 | SKU9,mug,12 |
The line is SKU9,mug,12, with no comma at the end, and each character was written once.
Real data brings edge cases.
For pieces = [], the loop does not run, and the builder is empty. The result is the empty string, with no separator.
For pieces = ["", "", ""] and the separator ,, the result is ,,. An empty piece is still a piece, so it still gets a separator in front of it.
For pieces = ["x", "y"] and an empty separator, the result is xy. The separator code runs, and it adds nothing.
For text = " ", every space comes while the builder is empty, so none is written. The result is the empty string, and the final cut does nothing.
This version builds the report with report = code + "|" + report in a Java loop. The answer is right, but each step copies the whole report so far.
Counterexample: 80,000 codes of 10 characters. The loop took 1,281 ms in Java in one run, and the builder took 0.6 ms for the same report. Both made the same text.
Collect the pieces in a builder and make the string once.
This version appends the separator after each piece. The last piece is followed by a separator that does not belong.
Counterexample: pieces = ["a", "b", "c"] and the separator -. The version returns a-b-c-. The correct result is a-b-c.
Put the separator before every piece except the first.
Appending the separator after every piece leaves a stray separator at the end, so the separator must go before every piece except the first.
This version removes the first character of a text with text = text[1:] until the text is empty. Each slice copies the rest of the text.
Counterexample: a text of 100,000 characters. The slices copy 4,999,950,000 characters in all, where reading the characters by index copies none.
Keep an index and read the characters in place.
This version reverses a text by reversing its UTF-8 bytes. A character such as é takes two bytes, and the reversed bytes are no longer valid text.
Counterexample: the text héllo has 5 characters and 6 bytes in UTF-8. Reversing the bytes and decoding them fails in Python with a decoding error.
Work with characters, and state the alphabet. This course uses ASCII text unless a problem says otherwise.
The word "length" means different things. The number of characters you see is not always the number a language returns.
| Text | Python len |
Java length() |
JavaScript length |
C++ size() |
UTF-8 bytes |
|---|---|---|---|---|---|
naïve |
5 | 5 | 5 | 6 | 6 |
| an emoji, U+1F600 | 1 | 2 | 2 | 4 | 4 |
Python counts code points. Java and JavaScript count UTF-16 units, so the emoji counts as 2. C++ std::string counts bytes, and the text is UTF-8 when it comes from a file or a network.
A single character on the screen can also be several code points, such as e with a combining accent. For ASCII text all of these agree.
The export adds a header line to a report that is built once: header + "\n" + body. That is one concatenation, with one copy, and it costs the same as any builder.
A builder is for loops that add pieces. Use plain concatenation when the text is built once from a few parts, and write the clearest code.
Your team lead brings four product changes.
A listing title has extra spaces, and the words must come in reverse order with one space between them. Scan from the end, find each word with two indexes, and append it to a builder. This is LeetCode 151: Reverse Words in a String.
Two invoice totals are digit strings too long for a 64-bit integer. Add them from the last digit, append each digit to a builder, and reverse the builder once at the end. This is LeetCode 415: Add Strings.
A receipt must show only the last four digits of a card number. Scan once, write a mask character for every earlier digit, and copy the last four.
A list of strings must travel as one text and be split back later. Write each string's length, a marker, and the string itself, so the decoder never has to guess where a string ends. This is LeetCode 271: Encode and Decode Strings.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate why adding lines to a string in a loop is slow, and what you do instead. Then say what it costs and one thing to check about the text. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have counted it.
A string cannot change, so in general each concatenation makes a new string and copies the old text. In a loop that is about n times n over two characters copied.
Instead I collect the pieces in a builder, a list with join, a StringBuilder or std::string with plus equals. I put the separator before every piece except the first, and I make the string once at the end.
That costs O of n for a text of n characters. I also state the alphabet, because length means different things in different languages.
Building a long string in a loop is slow if I add to a string each time. In Python, Java and JavaScript a string cannot change. In general every addition makes a new string and copies the old text, so n pieces copy about n squared over two characters. Some runtimes optimise simple cases, but none of them promises it.
I use a builder instead. In Python and JavaScript that is a list that I join at the end. In Java it is a StringBuilder, and in C plus plus it is std string with plus equals. I write each piece once, with the separator before every piece except the first, and I make the string once.
That costs O of n time for a text of n characters. Slicing in a loop has the same trap, because a slice copies, so I keep indexes instead.
I also state the alphabet. Length is code points in Python, UTF sixteen units in Java and JavaScript, and bytes in C plus plus. For ASCII all of them agree.
Checkpoint · Strings and builders
Q1/10 Why does adding one line at a time to a string in a long loop take so long?
Answer: B
A string cannot change in Python, Java and JavaScript, so in general every addition copies everything written so far. Some runtimes optimise simple cases, but none promises it.
Q2/10 The copies in the loop add up to about n * n / 2 lines of text. What happens to the work when the number of lines doubles?
Answer: C
n * n / 2 grows with the square of n, so doubling n makes about four times as many copies. The lesson's table shows this in each language.
Q3/10 Which method builds a long string in the right way?
Answer: C
A builder writes each piece once at its end, and the string is made once. The cost is the total length of the text.
Q4/10 You join the pieces "a", "b" and "c" with a dash. Where does the separator go in the loop?
Answer: C
That puts the dash between pieces only, so the result is a-b-c with no stray dash.
Q5/10 In Python, why do you not rely on s += t being fast in a loop?
Answer: B
CPython often appends in place, but that is not part of the language. The lesson's run, with the new code in front, was slow: 519 ms at 80,000 codes.
Q6/10 In C++, which line makes a temporary copy of the whole string at every step of a loop?
Answer: C
s + t builds a new string, and the assignment copies or moves it back. s += t appends in place.
Q7/10 In the lesson's runs, the JavaScript loop took under a millisecond at 80,000 codes. What is the right conclusion?
Answer: B
Engines such as V8 often keep a tree of pieces. The safe habit is still an array and join, which works in every engine.
Q8/10 A loop removes the first character of a text of 100,000 characters with text = text[1:] until the text is empty. About how many characters do the slices copy?
Answer: C
Each slice copies the rest of the text: 99,999 + 99,998 + ... + 0 = 4,999,950,000. Keep an index instead.
Q9/10 The text is one emoji, U+1F600. Which pair of lengths is right for Python and for Java?
Answer: C
Python counts code points, so it is 1. Java counts UTF-16 units, and this character needs 2. C++ std::string counts 4 bytes.
Q10/10 A report joins a header to a body once: header + "\n" + body. Is a builder needed?
Answer: B
A builder pays when a loop adds many pieces. For a few parts built once, plain concatenation is fine.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Join the log lines | Platform | Easy | A builder and the separator rule |
| 2 | Mask the card numbers | Pay | Easy | One scan with a builder, long runs of digits |
| 3 | Reverse words in a title | Stream | Easy | Indexes instead of slices |
Another problem, adding two long numbers as text, closes this stretch as part of its checkpoint.
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.