Count, compare and search strings efficiently, up to a first rolling hash.
You work on the search box of an online store. Shoppers type short texts such as Red Running Shoes, and your code has to read them. Your team lead lists three jobs:
All three jobs treat text as a string: a row of characters, one after another, in a fixed order. Most languages store a string like an array, so each character has an index that starts at 0.
| Index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Character | s | h | o | e | s |
The string shoes has length 5. Reading the character at index 3 is one step, however long the string is. The last character is at index length - 1.
A substring is a contiguous piece, such as hoe from index 1 to index 3. In Python, Java and C++, taking it builds a new string and copies its characters, so a slice costs time in proportion to its length. Some JavaScript engines share memory instead, but you cannot rely on that.
A loop that cuts one character off the front of a long string each time does a lot of hidden copying. Use an index that moves along the string instead.
A string that cannot be changed is immutable. To change one character you build a new string. Here is what a plain "change the first character" statement does.
| Language | s[0] = "S" on the string shoes |
|---|---|
| Python | Raises TypeError: 'str' object does not support item assignment |
| Java | No such statement. A String has no setter. A StringBuilder has setCharAt |
| JavaScript | Silently ignored in sloppy mode, and a TypeError in strict mode, which modules and classes use |
| C++ | Works. A std::string is mutable, so s[0] = 'S' changes it in place |
Your team lead's first job is an export file. You write a loop that adds each piece to the end of one string. The first attempt is correct.
text = ""
for piece in pieces:
text += pieceNow check the real size. In Java, where the same loop is text += piece;, every += builds a new string and copies all the characters so far. Take 100,000 pieces of two letters each. The loop copies 2 + 4 + 6 + ... + 200,000 characters, which is 10,000,100,000, about 10 billion.
The other languages differ, and the differences matter. This table comes from one quick test on a laptop with 100,000 pieces of two letters. Your times will differ, but the shape will not.
| Language and statement | What it does | Quick test |
|---|---|---|
Java s += piece |
Builds a new string every time | about 0.4 s |
Java StringBuilder and append |
Appends in place | under 1 ms |
Python s += piece |
CPython often extends the string in place, but the language does not promise it | about 0.01 s |
Python s = piece + s |
Builds a new string every time | about 0.3 s |
JavaScript s += piece |
V8 and the other big engines join lazily, with a structure called a rope, but the language does not promise it | about 3 ms |
C++ s += piece |
Appends in place, like a vector | under 1 ms |
C++ s = s + piece |
Builds a new string every time | about 0.2 s |
The safe habit is the same in every language: collect the pieces, then build the string once.
"".join(pieces).StringBuilder and append.pieces.join("").+= on one std::string.In Java, each plus equals on a string builds a new string and copies everything so far. A hundred thousand pieces copy about ten billion characters.
A computer stores each character as a number. In ASCII, the old standard for English text, the capital letters A to Z are 65 to 90. The small letters a to z are 97 to 122, the digits 0 to 9 are 48 to 57, and the space is 32.
So a minus A is 32. A letter minus a is its position in the alphabet, from 0 for a to 25 for z.
Unicode extends this to every writing system. It gives each character a number called a code point: é is 233, and the emoji 😀 is 128,512. A string of code points must then be stored as bytes, and the common way, UTF-8, uses 1 byte for ASCII, 2 for é and 4 for 😀.
That is why "the length of a string" depends on the language. Here is the length of four texts, as each language reports it.
| Text | Python len |
Java length() |
JavaScript length |
C++ size() |
|---|---|---|---|---|
abc |
3 | 3 | 3 | 3 |
é as one code point |
1 | 1 | 1 | 2 |
e plus a combining accent |
2 | 2 | 2 | 3 |
| 😀 | 1 | 2 | 2 | 4 |
Python counts code points. Java and JavaScript count UTF-16 units, where the emoji takes two. A C++ std::string counts bytes, here in UTF-8, the usual encoding for source files.
The same-looking é can be one code point or two. The two spellings are not equal until you normalise them. For ASCII text, as in the lab and the problems, every language agrees.
Predict what happens
Q In Java, a loop adds 100,000 pieces of two letters to a String with +=. About how many characters does it copy in all?
Answer: B
The copies grow by two letters each time: 2 + 4 + ... + 200,000 is 10,000,100,000. A StringBuilder appends in place and copies each character about once.
Each of the three jobs has an everyday picture. Keep them in mind while you read the steps in the next beat.
A post office has a rack with one pigeonhole for each letter of the alphabet. A clerk sorts a bag of mail by first letter, one item at a time. When she is done, she counts each hole to know how many items start with each letter.
The rack has 26 holes however big the bag is. This is counting with a fixed array: one slot for each possible letter, and one step for each item.
A post office rack counts mail by letter: one hole for each letter. A 26-slot array counts the letters of a text the same way.
You look for a station name in a long printed timetable line. You write the name on a paper strip and hold it under the line, with its first letter under the first letter of the line. You check the letters one at a time. At the first mismatch you slide the strip one place to the right.
This is plain pattern search: slide the pattern along the text, and compare at each shift.
Two people stand at the two ends of a long banner. Each reads towards the middle, one letter at a time, and they compare what they read. If every pair matches, the banner reads the same both ways. If one pair differs, they stop.
This is the two-pointer palindrome check: one pointer at each end, moving inwards.
Count the letters of banana. Make 26 slots, all 0, and give each letter its slot: a is slot 0, b is slot 1, and so on up to z in slot 25. For each letter of the word, add 1 to its slot.
| Letter read | b | a | n | a | n | a |
|---|---|---|---|---|---|---|
| Slot | 1 | 0 | 13 | 0 | 13 | 0 |
| Count afterwards | b 1 | a 1 | n 1 | a 2 | n 2 | a 3 |
After one pass, a holds 3, b holds 1 and n holds 2. Finding the count of a letter is one lookup.
Count the letters of banana with 26 slots. Each letter adds one to its own slot, and one pass gives a 3, b 1 and n 2.
Step by step: Counting the letters of banana. The animated player loads in your browser.
A map (a dictionary, HashMap, unordered_map or Map) can do the same job, and it keeps one entry for each letter that appears. The Hash table internals lesson showed how a map finds an entry. Here is how the two compare for banana.
| 26-slot array | Map | |
|---|---|---|
Memory for banana |
26 numbers, always | 3 entries |
| Finding a count | One index | One hash lookup |
| Works for | A small, fixed alphabet such as a to z |
Any characters, including all of Unicode |
Time for n letters |
One pass | One pass |
Use the array when you know the alphabet, such as lowercase letters, digits or ASCII (128 or 256 slots). Use a map when the text can hold anything. An array that covered every Unicode code point would need 1,114,112 slots.
Predict what happens
Q In the 26-slot count of banana, which slot does the letter n use?
Answer: B
The slot is the letter minus a, so it counts places after a, starting from 0. The letter n is the 14th letter, so it is 13 places after a. After the whole word is read, slot 13 holds 2.
Find the pattern abd in the text abcabcabd. Put the pattern at the start. At each shift, compare letter by letter, and stop at the first letter that differs.
| Shift | Letters compared | Result | Comparisons |
|---|---|---|---|
| 0 | a=a, b=b, c≠d | mismatch | 3 |
| 1 | b≠a | mismatch | 1 |
| 2 | c≠a | mismatch | 1 |
| 3 | a=a, b=b, c≠d | mismatch | 3 |
| 4 | b≠a | mismatch | 1 |
| 5 | c≠a | mismatch | 1 |
| 6 | a=a, b=b, d=d | match | 3 |
The pattern is found at shift 6, after 13 comparisons.
Plain search slides the pattern one place at a time and stops each shift at the first mismatch. Here abd is found at position 6 after 13 comparisons.
Step by step: Slide abd along abcabcabd. The animated player loads in your browser.
The text has 9 letters and the pattern has 3, so there are 7 shifts. In general there are n - m + 1 shifts for a text of n letters and a pattern of m letters, and each shift compares at most m letters. The cost is at most m × (n - m + 1).
The worst case is a text and a pattern that look alike for a long time. Take the text aaaaaaaaab and the pattern aaab. Every shift matches 3 letters before it fails, and the last shift matches all 4, so it takes 4 × 7 = 28 comparisons. For a text of 1,000,000 letters and a pattern of 1,000 letters, the worst case is 999,001,000 comparisons, about a billion.
Step by step: The worst case for plain search. The animated player loads in your browser.
Exercise · Predict the output: Comparisons to find aab in aaab. This search counts every comparison it makes, including the one that fails. What does it print?
text = "aaab"
pattern = "aab"
comparisons = 0
found = -1
for shift in range(len(text) - len(pattern) + 1):
matched = 0
while matched < len(pattern):
comparisons += 1
if text[shift + matched] != pattern[matched]:
break
matched += 1
if matched == len(pattern):
found = shift
break
print(found, comparisons)Two faster methods exist, and they are only named here. A rolling hash keeps one number for the window of text under the pattern, and updates it in constant time when the window slides. It compares that number with the pattern's number, and checks the letters only when the numbers agree.
KMP (Knuth, Morris and Pratt) studies the pattern first, so that after a mismatch it knows how much of the pattern still matches. Its place in the text never moves backwards, and it takes time in proportion to n + m, even in the worst case.
A rolling hash does the same on average, but it can be slower if many windows share a number by accident. You will not need to derive either for the warm-up problems.
A palindrome reads the same forwards and backwards, such as level. For sentences, you first ignore case and anything that is not a letter or a digit. Madam, I'm Adam becomes madamimadam, which is a palindrome.
You could build the reversed string and compare it with the original. That works, and it uses a second string of the same size.
The two-pointer way needs no second string. Put one pointer at each end and move both inwards. Skip a character that is not a letter or a digit, and compare the two that are left, ignoring case. One mismatch settles the answer.
Reversing a string takes one line in each language.
| Language | Reverse s |
Note |
|---|---|---|
| Python | s[::-1] |
Builds a new string |
| Java | new StringBuilder(s).reverse().toString() |
Keeps an emoji in one piece |
| JavaScript | [...s].reverse().join("") |
s.split("").reverse().join("") breaks an emoji |
| C++ | std::reverse(s.begin(), s.end()) |
Works in place, because a std::string is mutable |
Reversing by code point can still pull an accent away from its letter. For text that people write, use a library that knows about it.
A palindrome check puts a pointer at each end, skips anything that is not a letter or a digit, and compares the rest ignoring case.
Step by step: Two pointers on Madam, I'm Adam. The animated player loads in your browser.
You met two pointers closing in from both ends in the Opposite ends lesson. Here the data is a string, and the pointers also skip characters.
Exercise · Put it in order: The pointers that meet in the middle. Arrange the lines into a function that says whether a lowercase word reads the same backwards.
def is_palindrome(text):
left, right = 0, len(text) - 1
while left < right:
if text[left] != text[right]:
return False
left += 1
right -= 1
return True
return TruePredict what happens
Q The text is aaaaaaaaab and the pattern is aaab. At shift 0, how many letters are compared before the mismatch?
Answer: C
The pattern letters a, a and a match the text. The fourth comparison, text a against pattern b, fails. The mismatch counts as a comparison, so shift 0 costs 4.
Pick a problem, then step through it forwards and back. In a search, matched letters are tinted and the mismatch is outlined in the warning colour. In a count, the slot being updated is outlined.
Try these four, in order:
n?The visualizer: pick a grid or a map, then step through the algorithm on it. It loads in your browser.
Each method keeps one fact true after every step. Say the fact, and the correctness follows.
While counting, each of the 26 slots holds how many times its own letter appears in the part of the word read so far.
When the last letter has been read, "the part read so far" is the whole word, so each slot holds the final count.
At every shift, all earlier shifts have already failed, and the pattern letters before the first mismatch equal the text letters under them.
So the first shift where all m letters match is the first place the pattern occurs. If no shift matches, the pattern is not in the text.
Every pair of characters outside the two pointers has already matched, so only the characters between the pointers are left to check.
When the pointers meet, nothing is left to check, and the text is a palindrome.
Counting letters, with one slot for each letter from a to z.
def letter_counts(word):
# [1] Make 26 slots, all 0: slot 0 is for a, slot 1 for b, and so on up to slot 25 for z.
counts = [0] * 26
for ch in word:
# [2] The letter minus a is its slot. Add 1 to that slot.
counts[ord(ch) - ord("a")] += 1
# [3] Slot k now holds how many times the letter k places after a appears.
return countspublic int[] letterCounts(String word) {
// [1] Make 26 slots, all 0: slot 0 is for a, slot 1 for b, and so on up to slot 25 for z.
int[] counts = new int[26];
for (int i = 0; i < word.length(); i++) {
// [2] The letter minus a is its slot. Add 1 to that slot.
counts[word.charAt(i) - 'a']++;
}
// [3] Slot k now holds how many times the letter k places after a appears.
return counts;
}vector<int> letterCounts(string word) {
// [1] Make 26 slots, all 0: slot 0 is for a, slot 1 for b, and so on up to slot 25 for z.
vector<int> counts(26, 0);
for (char ch : word) {
// [2] The letter minus a is its slot. Add 1 to that slot.
counts[ch - 'a']++;
}
// [3] Slot k now holds how many times the letter k places after a appears.
return counts;
}function letterCounts(word) {
// [1] Make 26 slots, all 0: slot 0 is for a, slot 1 for b, and so on up to slot 25 for z.
const counts = new Array(26).fill(0);
for (let i = 0; i < word.length; i++) {
// [2] The letter minus a is its slot. Add 1 to that slot.
counts[word.charCodeAt(i) - 97]++;
}
// [3] Slot k now holds how many times the letter k places after a appears.
return counts;
}Plain pattern search, with the text, the pattern and a shift.
def find_first(text, pattern):
n = len(text)
m = len(pattern)
# [1] Try every shift. The pattern's first letter sits over text[shift], and the last shift that fits is n - m.
for shift in range(n - m + 1):
matched = 0
# [2] Compare letter by letter, and stop at the first letter that differs.
while matched < m and text[shift + matched] == pattern[matched]:
matched += 1
# [3] If every letter matched, the pattern starts at this shift.
if matched == m:
return shift
return -1public int findFirst(String text, String pattern) {
int n = text.length();
int m = pattern.length();
// [1] Try every shift. The pattern's first letter sits over text[shift], and the last shift that fits is n - m.
for (int shift = 0; shift + m <= n; shift++) {
int matched = 0;
// [2] Compare letter by letter, and stop at the first letter that differs.
while (matched < m && text.charAt(shift + matched) == pattern.charAt(matched)) {
matched++;
}
// [3] If every letter matched, the pattern starts at this shift.
if (matched == m) {
return shift;
}
}
return -1;
}int findFirst(string text, string pattern) {
int n = text.size();
int m = pattern.size();
// [1] Try every shift. The pattern's first letter sits over text[shift], and the last shift that fits is n - m.
for (int shift = 0; shift + m <= n; shift++) {
int matched = 0;
// [2] Compare letter by letter, and stop at the first letter that differs.
while (matched < m && text[shift + matched] == pattern[matched]) {
matched++;
}
// [3] If every letter matched, the pattern starts at this shift.
if (matched == m) {
return shift;
}
}
return -1;
}function findFirst(text, pattern) {
const n = text.length;
const m = pattern.length;
// [1] Try every shift. The pattern's first letter sits over text[shift], and the last shift that fits is n - m.
for (let shift = 0; shift + m <= n; shift++) {
let matched = 0;
// [2] Compare letter by letter, and stop at the first letter that differs.
while (matched < m && text[shift + matched] === pattern[matched]) {
matched++;
}
// [3] If every letter matched, the pattern starts at this shift.
if (matched === m) {
return shift;
}
}
return -1;
}The library has its own search (find, indexOf, in). Use it in real code: it is tuned and it is shorter. Remember that a language does not always promise linear time in the worst case, so a long text and a long repetitive pattern can still be slow.
Exercise · Find the bug: The match at the very end. This search returns the first shift where the pattern matches, or -1. It misses a pattern that sits at the very end of the text. Which line is wrong?
def find_first(text, pattern):
n = len(text)
m = len(pattern)
for shift in range(n - m):
matched = 0
while matched < m and text[shift + matched] == pattern[matched]:
matched += 1
if matched == m:
return shift
return -1Predict what happens
Q Searching for a pattern of 4 letters in a text of 10 letters, how many shifts are there?
Answer: C
The pattern fits at start positions 0, 1, ..., n - m, which is 0 to 6 for n = 10 and m = 4. That is n - m + 1 = 7 shifts.
The third template builds one string from many pieces. It is the fix for the first attempt in the first beat: collect the pieces, then build once.
def join_words(words):
# [1] Start with an empty builder. Adding to it does not copy all the text built so far each time.
pieces = []
for word in words:
# [2] Add each word to the end of the builder.
pieces.append(word)
# [3] Build the string once, at the end.
return "".join(pieces)public String joinWords(String[] words) {
// [1] Start with an empty builder. Adding to it does not copy all the text built so far each time.
StringBuilder builder = new StringBuilder();
for (String word : words) {
// [2] Add each word to the end of the builder.
builder.append(word);
}
// [3] Build the string once, at the end.
return builder.toString();
}string joinWords(vector<string> words) {
// [1] Start with an empty builder. Adding to it does not copy all the text built so far each time.
string builder;
for (const string& word : words) {
// [2] Add each word to the end of the builder.
builder += word;
}
// [3] Build the string once, at the end.
return builder;
}function joinWords(words) {
// [1] Start with an empty builder. Adding to it does not copy all the text built so far each time.
const pieces = [];
for (const word of words) {
// [2] Add each word to the end of the builder.
pieces.push(word);
}
// [3] Build the string once, at the end.
return pieces.join("");
}To compare two strings, walk both from the left to the first character that differs. That character's code decides which string is smaller. If one string is the start of the other, the shorter one is smaller.
| Pair | Why | Smaller |
|---|---|---|
apple and apricot |
p and r differ first, and p is 112 and r is 114 |
apple |
app and apple |
app is the start of apple |
app |
Zebra and apple |
Z is 90 and a is 97, so capitals come first |
Zebra |
10 and 9 |
1 is 49 and 9 is 57, so the first character decides |
10 |
Code order is not what people expect. A sort by code puts every capital letter before every small letter, and puts ä (code 228) after z (code 122). Programs that sort text for people use a collation, a table of rules for a language, such as localeCompare in JavaScript or Collator in Java.
Two more cautions. In JavaScript, [10, 9, 1].sort() gives [1, 10, 9], because the default sort compares numbers as strings. And in Java, == on strings compares references, so use equals to compare the characters.
A subsequence keeps the order of the characters but may skip some. A substring may not skip any. ace is a subsequence of abcde, but it is not a substring.
Of the string abcd |
Count |
|---|---|
| Substrings (non-empty, counted by position) | 10 |
| Subsequences (non-empty, counted by position) | 15 |
For n characters, there are n × (n + 1) / 2 substrings and 2^n - 1 non-empty subsequences. At 40 characters that is 820 against 1,099,511,627,775. Plain search looks for a substring. Fuzzy search, where typing bkpr finds bookkeeper, looks for a subsequence, and it is done with one pointer in each string, not by listing them.
Tokenising cuts text into pieces, called tokens, at separators such as spaces or commas. Parsing then reads each token by its meaning, such as a number, a word or a command. Search engines tokenise a description into words before they index it.
The usual tool is split, and its edge cases differ by language.
| Call | Python and JavaScript | Java |
|---|---|---|
"a,b,," split on a comma |
["a", "b", "", ""] (4 pieces) |
["a", "b"] (2 pieces, trailing empty pieces dropped) |
"a b" split on a space |
["a", "", "b"] |
["a", "", "b"] |
C++ has no split. You find each separator with find and cut with substr, or read from a std::istringstream. To split on any amount of spaces in Python, call split() with no argument.
Now write it yourself. The third job was to find a word inside a long product description, and the store wants to highlight every place the word appears, not only the first.
The lab has one function, find_all(text, pattern). It returns the list of every position where the pattern starts, from smallest to largest.
It is the slide and compare from the second beat, with two changes: it keeps going after a match, and it collects the shifts that matched. Here is a small run with the text abababa and the pattern aba.
| Shift | Letters compared | Result | Comparisons |
|---|---|---|---|
| 0 | a=a, b=b, a=a | match: keep 0 | 3 |
| 1 | b≠a | mismatch | 1 |
| 2 | a=a, b=b, a=a | match: keep 2 | 3 |
| 3 | b≠a | mismatch | 1 |
| 4 | a=a, b=b, a=a | match: keep 4 | 3 |
The text has 7 letters and the pattern has 3, so the last shift is 7 - 3 = 4. The answer is [0, 2, 4], after 11 comparisons.
The matches overlap: the match at 0 ends with the a at position 2, and the match at 2 starts with it. A loop that jumps past a match, to shift 3, would try only shifts 3 and 4, and would return [0, 4].
Exercise · Break it: Find the input where matches overlap. This function should return every position where the pattern starts. After a match it jumps past the whole pattern. Find an input where it misses a match.
def find_all(text, pattern):
found = []
if not pattern:
return found
shift = 0
while shift <= len(text) - len(pattern):
if text[shift:shift + len(pattern)] == pattern:
found.append(shift)
shift += len(pattern)
else:
shift += 1
return foundThree rules keep it correct:
n - m, and include n - m. A match at the very end, such as ab at 3 in abcab, is the one an off-by-one misses.aa appears in aaaa at 0, 1 and 2.n and m as int: with the unsigned size_t, text.size() - pattern.size() wraps round to a huge number instead of going below 0.The library can do this too, with a loop around find or indexOf that starts each new search one place after the last match. Starting it after the end of the last match skips the overlapping ones, the same bug as the jump.
Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
| Question | Count letters | Slide and compare | Two pointers |
|---|---|---|---|
Time for n characters |
One pass: O(n) | At most m × (n - m + 1) comparisons |
One pass: O(n) |
| Memory | 26 slots: O(1), or O(k) for a map of k letters |
O(1) | O(1) |
| Stops early? | No, every letter is read once | Yes, a mismatch ends a shift | Yes, one mismatch ends it |
| Worst case | The same as the best case | A text and a pattern that repeat a letter | A palindrome, or a mismatch in the middle |
Two more costs to remember. Building a string from n pieces in one go costs time in proportion to the total length. Copying the whole string at every step costs about the square of the length. Cutting a slice costs its length.
Use the 26-slot array when the characters come from a small, fixed set. Use two pointers when a property is symmetric, such as a palindrome, or when you compare two strings from both ends.
Use plain slide and compare when the pattern is short or the text is not repetitive. Call the library's search first, and think about a rolling hash or KMP only when a repetitive input makes it slow.
Do not use a 26-slot array for text that may hold accents, emoji or other scripts. Use a map keyed by code point, or by the user-visible character.
Do not sort or compare text for people by code alone. Use a collation. And do not run plain slide and compare on a long, repetitive text with a long, repetitive pattern, because m × (n - m + 1) can reach a billion.
counts[ord(ch) - ord("a")] += 1 assumes a lowercase letter. For Z, the value is 90 - 97 = -7. In Python a negative index counts from the end, so counts[-7] is slot 19, the slot for t. There is no error, and Z is counted as a t.
In Java the same line throws ArrayIndexOutOfBoundsException. In JavaScript it writes a property named -7 on the array, and no slot changes. In C++ it writes outside the array, which is undefined behaviour. Lower-case the letter first, or check its range.
A capital Z minus a is minus seven. In Python that counts from the end, so Z is counted as t with no error. Lower-case letters first.
if text.find("apple"): looks like "is it there". But find returns the index, and it is 0 when the word is at the start, which is false, and -1 when it is missing, which is true. In JavaScript, indexOf does the same. In C++, text.find("zzz") returns npos, a large number, which is also true.
For text = "apple pie", text.find("apple") is 0 and text.find("zzz") is -1. Compare with -1, or use in in Python and includes in JavaScript.
In Java, == on strings asks whether two names point at the same object. new String("kayak") == "kayak" is false, even though both hold kayak. Literals can share one object, so "kayak" == "kayak" is true, and the bug hides in tests.
Use a.equals(b). Python, JavaScript and C++ compare the characters with ==.
"😀".length is 2 in JavaScript, and "😀".length() is 2 in Java, because they count UTF-16 units. Cutting such a string at index 1 splits the emoji and leaves a broken character. The reversal idiom s.split("").reverse().join("") in JavaScript breaks every emoji.
Use [...s] in JavaScript, codePointCount in Java, and a library that counts grapheme clusters, such as Intl.Segmenter, when you need the characters people see.
"a b".split(" ") is ["a", "", "b"] in Python, Java and JavaScript. The two spaces leave an empty string in the middle, and a loop that reads each piece as a number or a word fails on it. In Python, "a b".split() drops empty pieces.
Decide what an empty piece means before you split, and test a text with two spaces in a row.
while s: s = s[1:] cuts the first character off each time. In Python each slice copies the rest. A string of 200,000 characters then copies about 20 billion characters in all, and a quick test took about half a second. Move an index along the string, as in i += 1, and nothing is copied.
std::string can.+= in a loop copies the whole string every time in Java. Collect the pieces and build once. Python, JavaScript and C++ often hide the cost, but only a join or an in-place append promises it.m × (n - m + 1) comparisons. A rolling hash and KMP are faster. Tokenise once, and read each token by its meaning.Explain the three methods in your own words, then take the checkpoint quiz. The checkpoint counts when you pass both the quiz and the lab.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · Strings as arrays
Q1/2 In Python, s = "shoes" and then s[0] = "S" runs. What happens?
Answer: C
Python, Java and JavaScript strings are immutable. To get "Shoes" you build a new string, for example "S" + s[1:]. A C++ std::string is mutable, so s[0] = 'S' works there.
Q2/2 In Java, a loop adds 100,000 pieces of two letters to a String with +=. Why is it slow?
Answer: C
A String cannot be changed, so every += makes a new one. The copies grow 2, 4, 6, up to 200,000 characters. A StringBuilder appends in place and copies each character about once.
Checkpoint · Characters
Q1/2 What do len("😀") in Python and "😀".length in JavaScript return?
Answer: B
Python counts code points, and the emoji is one. JavaScript counts UTF-16 units, and the emoji takes two. A C++ std::string counts bytes, and the same emoji is 4.
Q2/2 In a count with 26 slots, which slot does the letter e use?
Answer: B
The slot is the letter minus a, so a is 0, b is 1, c is 2, d is 3 and e is 4. The fifth letter is 4 places after the first.
Checkpoint · Array or map
Q1/2 When should you count characters with a map instead of 26 slots?
Answer: C
An array of 26 slots covers only the letters a to z. A map keeps one entry for each character that really appears, so it works for any text. An array for all of Unicode would need 1,114,112 slots.
Q2/2 Which of 10 and 9 is smaller when you compare them as strings, by character codes?
Answer: B
Strings are compared from the left, and the first different character decides: 1 is 49 and 9 is 57. That is why JavaScript's default sort puts 10 before 9.
Checkpoint · Substrings and search
Q1/2 Which statement about "ace" and "abcde" is true?
Answer: B
A substring is a contiguous piece, and a, c, e are not next to each other in abcde. A subsequence keeps the order and may skip letters, so a, c, e is one.
Q2/2 Plain pattern search looks for a pattern of 3 letters in a text of 12 letters. At most how many comparisons does it make?
Answer: C
There are n - m + 1 = 10 shifts, and each compares at most m = 3 letters, so at most 3 × 10 = 30. Not 36, which would be 3 × 12.
Checkpoint · Palindromes and splitting
Q1/2 Ignoring case, spaces and punctuation, which of these is a palindrome?
Answer: C
steponnopets reads the same both ways: s t e p o n n o p e t s. Madam, I am Adam gives madamiamadam, which differs from its reverse. Step on no pet and Level up also differ.
Q2/2 What does "a,b,,".split(",") give in Java and in Python?
Answer: C
Python and JavaScript keep the empty pieces: "a", "b", "" and "". Java's split(",") removes the empty pieces at the end of the result, which leaves "a" and "b". Check the call for the language you use.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Visualiser and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.