Bitpath

Lesson 1 · Unit 03

Strings don't change

Every edit builds a new string

11 exercisesabout 3 min

What you practise

  • Immutability
  • += in a loop is O(n²)
  • Collect and join

Try a question from this lesson

Pick one

This tries to turn "cat" into "bat" by overwriting one character. What happens?

word = "cat"
word[0] = "b"
print(word)
let word = "cat";
word[0] = "b";
console.log(word);
let word = "cat";
word[0] = "b";
console.log(word);

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Read-only characters

A string is an array of characters you can read but never write. Every "change" builds a brand-new string and copies the characters across.

So adding one character to a string of n characters costs O(n), not O(1).

s = "cat"
t = s + "s"         # new string, O(n)
print(s, t)
print(s[0], len(s)) # reads are O(1)
const s = "cat";
const t = s + "s";  // new string, O(n)
console.log(s, t);
console.log(s[0], s.length);  // O(1)
const s = "cat";
const t = s + "s";  // new string, O(n)
console.log(s, t);
console.log(s[0], s.length);  // O(1)

Concept

Collect, then join

The fix: push the pieces into a list, which is O(1) each, and join them once at the end. The join copies every character exactly once, so the whole build is O(n).

def shout(words):
    parts = []
    for w in words:
        parts.append(w.upper())
    return " ".join(parts)
function shout(words) {
  const parts = [];
  for (const w of words) {
    parts.push(w.toUpperCase());
  }
  return parts.join(" ");
}
function shout(words: string[]): string {
  const parts: string[] = [];
  for (const w of words) {
    parts.push(w.toUpperCase());
  }
  return parts.join(" ");
}

Python noteThe separator comes first in Python: " ".join(parts). CPython often makes += fast, but only join is guaranteed to be linear.

JavaScript noteHere the list comes first: parts.join(" "). Engines often make += fast, but joining is the pattern that is linear everywhere.

TypeScript noteconst parts: string[] = [] says what the empty array will hold, so a stray parts.push(42) is a compile error.

8 more exercises in the app

  • 2× type the answer
  • 1× fill the blanks
  • 2× multiple choice
  • 1× true or false
  • 1× order the lines
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy