Strings in memory: immutability and building strings efficiently

Video lessonComing soon

1 A loop that looks like one pass

We want to reverse the word "drawer". Read backwards, it spells "reward". The first loop most of us write takes the letters from the end and adds each one to a result:

result = ""
for i from n − 1 down to 0
    result = result + word[i]

It looks like one pass over the word, so O(n). In many languages, it is O(n²). On a word of 10⁶ characters, it gets Time Limit Exceeded (TLE).

The reason is how a string sits in memory, and what + has to do with it. Once we see that, building strings fast takes one small change.

2 An array of characters, and characters are numbers

A string is an array of characters, side by side in memory. So reading s[i] is O(1), and so is reading its length, which the string keeps.

Each box holds a small number, the character code. For English letters, digits and signs, the codes come from ASCII:

d100r114a97w119e101r114
'drawer' in memory: under each letter is the code stored in its box

The codes follow the order we expect, in three runs:

CharactersCodes
'0' to '9'48 to 57
'A' to 'Z'65 to 90
'a' to 'z'97 to 122

Because each run has no gaps, subtraction turns a character into something useful:

  • c - 'a' is the letter's place. 'a' gives 0 and 'w' gives 22. This is the 26-slot count array from the counting lesson.
  • c - '0' is the digit's value. '7' − '0' = 55 − 48 = 7. A digit inside a string is a character, not a number, until we do this.
  • Upper and lower case are 32 apart. 'w' is 119 and 'W' is 87.

Comparing two characters compares their codes. So 'e' < 'n', and every capital comes before every small letter: 'Z' (90) < 'a' (97).

C++

A char is a number. c - 'a' and '7' - '0' work as written, and s[3] is O(1).

charAt, not []. A String is read with charAt(i), and the char it gives is a number.

No character type. s[3] is a string of length 1. ord gives its code, and chr turns a code back into a character.

No character type. s[3] is a string of length 1. charCodeAt(0) gives its code, and String.fromCharCode turns a code back.

Bytes. s[3] is a byte, and len(s) counts bytes. For English letters, one byte is one character.

Bytes, not s[i]. A str cannot be indexed with s[i], because some characters take more than one byte. For English letters, as_bytes()[i] gives the code in O(1).

A char is a number. c - 'a' and '7' - '0' work as written, and s[3] is O(1).

3 Strings that never change

In most languages, a string is immutable: once it is made, no box in it can change. Writing s[0] = 'D' to get "Drawer" shows which kind of string a language has:

C++

Mutable. A string can change. s[0] = 'D' makes it "Drawer" in O(1), with no copy.

Immutable. A String has no way to set a character, so s.charAt(0) = 'D' is a Compile Error.

Immutable. s[0] = "D" is a Runtime Error.

Immutable. s[0] = "D" changes nothing. Outside strict mode it gives no error either, so s quietly stays "drawer".

Immutable. s[0] = 'D' is a Compile Error.

Mutable, but not by index. A String can grow at the end, but s[0] = 'D' is a Compile Error. To change one character, we turn it into an array first.

Immutable. s[0] = 'D' is a Compile Error.

Languages do this so strings are safe to share. t = s costs one step, as with arrays, and nothing done through t can change s. A string used as a map key also never changes under the map.

The price is that every change makes a new string. Methods that seem to change a string, like making it upper case or replacing a letter, build a new one and return it. The old one stays as it was. Even a one-letter change copies all n characters.

4 Why + in a loop costs O(n²)

We go back to the loop from the start. Since result cannot grow, result + word[i] asks for a new block one box longer. It copies every character of result into it, then writes the new one. The steps below build "reward". Orange boxes are copied, and the blue box is the new character:

result = result + word[i], for 'drawer'
d0r1a2w3e4r5i
word
r
A new string of 1: copy 0, write 'r'. Written so far: 1

Each step writes one more character than the step before. Drawn as bars, the writes make a staircase:

123456
Characters written at each step: 1 + 2 + 3 + 4 + 5 + 6 = 21

The staircase fills about half of a 6 by 6 square. For a word of n characters, it fills about half of an n by n square:

1 + 2 + … + n = n(n + 1) / 2, about n² / 2

So the loop is O(n²). At n = 10⁵, it copies around 5 × 10⁹ characters. Copying is one of the fastest things a computer does, so this can still squeeze in. At n = 10⁶, it is around 5 × 10¹¹, far past the time limit, and it gets TLE. The answer itself has only n characters. Almost all that work is copying the same characters again and again.

Here is what your language does with this loop:

C++

Depends on how it is written. result = result + c builds a new string each time, so it is O(n²). result += c adds to the end of result itself, so it is fast.

O(n²). Each + makes a new String and copies the old one into it.

O(n²) by the rules. CPython can sometimes grow the string in place when nothing else uses it, but the language does not promise this, and putting a character in front always copies.

Usually fast. JavaScript engines keep the pieces and join them once, when the string is read. So += in a loop is fine in practice.

O(n²). Each + makes a new string and copies the old one into it.

Fast at the end. A String grows at the end like a Vec, so push is fast. The copies come back with format!, or when new text goes in front.

O(n²). Each + makes a new string and copies the old one into it.

5 Building with a buffer

The fix is to collect the characters somewhere that can grow, and make the string once at the end. That place is a string builder: the string itself, with +=.

A builder is a dynamic array of characters, the kind from the lesson on arrays in memory. It keeps spare room at the end. So each append writes one character, and only a full buffer gets copied, into a block twice the size.

r0e1w234567
A builder after 3 appends: 'w' went into spare room, nothing was copied

For "drawer", every tab returns "reward". The loop is the one from section 1. Only the place the characters go has changed.

The n appends cost about 2n steps, counting the rare copies when the buffer doubles. Making the string at the end copies n characters once. So the loop is O(n) time and O(n) space. At n = 10⁶, that is a few million steps instead of 5 × 10¹¹.

6 Editing in place with an array

A builder is right when we make a new string from left to right. Some changes rewrite characters where they are instead: swapping two, or replacing one. For those, we copy the string into a character array once, edit the array as much as we like, and turn it back into a string at the end.

Reversing works this way too. Two indexes start at the two ends. We swap their characters, move both inwards, and stop when they meet:

Reversing 'drawer' in a character array
d0r1a2w3e4r5ij
Start: i at the front, j at the back
StepijArray after the swap
105r r a w e d
214r e a w r d
323r e w a r d

Six characters took three swaps. Each swap fixes both ends of what is left, so n characters take about n/2 swaps.

The swaps take O(n) time. With an immutable string, the copy into an array and the copy back take O(n) space. When the string can change in place, or a problem hands us the characters as an array, no extra space is needed.

C++

No copy needed. The function changes the caller's string through the &, so "drawer" becomes "reward" with O(1) extra space.

toCharArray and new String. Each copies all n characters once.

list and join. list(word) copies the characters into a list, and ''.join makes the string once.

split('') and join(''). Each copies all n characters once.

[]byte(word) and string(chars). Each copies all n bytes once.

Vec<char>. It holds whole characters, so a swap never splits one. An empty word would make len() - 1 go below 0, and a usize cannot hold a negative number, so the function returns early.

ToCharArray and new string. Each copies all n characters once.

7 Substrings and comparing

A substring is a piece of a string that sits together, like "raw" at indexes 1 to 3 of "drawer". Most languages take the piece by its start and its end, where the end is the index just after the last character:

d0r1a2w3e4r5startend
'raw' runs from start = 1 up to, but not including, end = 4

Taking a substring usually copies its k characters, so it costs O(k) time and space. Inside a loop, that copy is easy to miss.

Comparing two strings walks along both from index 0 and stops at the first difference. "drawer" and "drawn" agree on four characters, in orange, then differ at index 4, in blue:

d0r1a2w3e4r5
drawer
d0r1a2w3n4
drawn: 'e' (101) < 'n' (110), so drawer comes first

So comparing costs up to the length of the shorter string, not one step. Two equal strings are the slowest case, because every character gets checked. Sorting or checking many strings costs that length on every comparison.

C++

substr takes a length, not an end. s.substr(1, 3) means 3 characters from index 1. It copies them, O(k).

substring takes an end, and copies. s.substring(1, 4) stops before index 4 and costs O(k). Compare contents with equals, never ==.

A slice takes an end, and copies. s[1:4] stops before index 4 and costs O(k).

slice takes an end. s.slice(1, 4) stops before index 4. Count it as O(k): engines sometimes share the memory instead, but the language does not promise it.

A slice takes an end, and shares. s[1:4] stops before index 4. It points into the same memory, so it costs O(1). This is safe, because neither string can change.

A slice takes an end, and borrows. &s[1..4] stops before index 4 and costs O(1). The indexes count bytes, so with English letters they match the characters.

Substring takes a length, not an end. s.Substring(1, 3) means 3 characters from index 1. It copies them, O(k).

8 Mistakes, and what these problems need

  • Adding to a string in a loop. On a word of 10⁶ characters, the loop from section 1 copies around 5 × 10¹¹ characters and gets TLE.
  • Off by one at the end of a substring. "raw" in "drawer" runs from index 1 to 3. So its end is 4, and its length is 3. Mixing the two up gives "ra" or "rawe", a Wrong Answer.
  • Calling a method and dropping its result. Making s upper case on a line of its own leaves s as "drawer". The new string came back as the result, and nothing kept it.
  • Taking a substring to drop the first character, again and again. Each call copies the rest of the string, so n of them cost about n²/2 copies, the same staircase as section 4. An index that moves forward does the same job in O(1).

C++

substr(1, 4) is "rawe". Its second number is a length, so passing an end index gives a piece that is too long.

== compares objects, not text. Two strings with the same letters, built separately, can fail a == b. Use a.equals(b).

A slice never complains. s[1:100] stops quietly at the end, so a wrong bound gives a Wrong Answer, not an error.

Use === and slice. The old substr(1, 3) takes a length, unlike slice and substring.

len counts bytes. A letter outside English, like é, takes two bytes, so len("é") is 2.

A slice through a character panics. &s[0..1] on "é" is a Runtime Error, because it cuts a two-byte character in half.

Substring(1, 4) is "rawe". Its second number is a length, so passing an end index gives a piece that is too long.

The problems in this subtopic reverse, compare or rebuild a string one character at a time. They come in three shapes:

  • Rebuild a string. Squeezing repeated letters, joining words, saying what a string looks like: append to a builder, one character or piece at a time.
  • Change characters where they are. Reversing, or swapping letters: copy into a character array and move two indexes.
  • Read and compare. Checking a palindrome, a common prefix, or a digit: read s[i] by index and use the codes. No new string is needed at all.

The habit to keep: before writing + or a substring inside a loop, ask whether it copies the whole string every time. If it does, a builder, an array or an index does the same job in O(n).

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.