Lesson 1 · Unit 03
Strings don't change
Every edit builds a new string
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);Correct answer
It raises a TypeError
It prints cat
It does not compile
Why
Strings are immutable: no character can be overwritten. Python raises a TypeError, JavaScript silently ignores the assignment, and TypeScript refuses to compile it. The string is still "cat" every time.
JavaScript noteIn strict mode (modules and classes) the assignment throws a TypeError instead of being ignored.
TypeScript noteThe error reads: index signature in type String only permits reading.
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.