Build strings efficiently in each language and avoid quadratic concatenation.
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.
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("");
}def 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("");
}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.
This version appends the separator after each piece. The last piece is followed by a separator that does not belong.
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.
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.
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.
systemdesignmastery.dev/dsa/cheatsheets/strings-and-builders