Lesson 36 of 40Strings, math and design
String Algorithms
What strings really cost, anagram and palindrome tricks, KMP's prefix function, Rabin-Karp rolling hashes, and the Unicode traps that break string code.
A log search scans gigabytes for an error code. A plagiarism checker looks for long passages that appear in two documents. A genomics pipeline finds every 10-letter DNA sequence that repeats. A username validator rejects a name that "looks" 8 characters long but has a length of 11. This last unit collects the topics that sit outside the big pattern families: strings, math, class design and range queries. Strings are the most common data you will handle at work, and they hide costs: a loop that looks linear can be quadratic, and a length that looks obvious depends on the language. This lesson starts with those costs, then covers the patterns interviewers reach for (frequency counts, palindromes) and the two classic matching algorithms, KMP and Rabin-Karp, that turn an O(n × m) search into O(n + m).
What strings cost
Strings are immutable in Python, JavaScript, Java, C# and Go. Every operation that "changes" a string builds a new one. That has three consequences that show up in interviews and in production profiles.
Concatenation in a loop. s += piece creates a new string and copies everything so far. Do that n times and you copy 1 + 2 + … + n characters: O(n^2). The fix is to collect pieces in a list and join once at the end, which is O(total length).
# O(n^2) in general: each += can copy the whole string so far
out = ""
for word in words:
out += word + ","
# O(n): one copy at the end
out = ",".join(words)There is a subtlety seniors know. CPython has an optimisation that sometimes resizes the string in place when nothing else references it, so the slow version may look fine in a quick test. PEP 8 explicitly says not to rely on it, because it is a CPython detail that other implementations do not have and that breaks as soon as a second reference exists. Modern JavaScript engines represent += results lazily as a rope, so += in a loop is usually fast in Node too, but parts.join("") is still the idiomatic choice. In Java, use a StringBuilder.
Slicing copies. In Python s[1:] copies n - 1 characters. A recursive function that passes s[1:] down at each level does O(n^2) work in copying alone, before any real logic. Pass indices (lo, hi) instead of slices. The same applies to s[::-1] inside a loop.
Comparing and hashing are O(length). a == b on two strings of length m is O(m), and so is using a string as a dict key the first time (Python caches a string's hash after computing it once). When you put every substring of length k into a set, the cost is O(n × k), not O(n). That is fine when k is 10 and a problem when k is n/2, which is exactly the gap rolling hashes fill.
Frequency counts as keys
Most anagram problems reduce to "do these two strings have the same character counts?" For lowercase English letters, a list of 26 counts is the cheapest exact signature. Sorting each word also works but costs O(k log k) per word instead of O(k).
- Group Anagrams: the key is
tuple(counts)(a list cannot be a dict key; a tuple can). - Find All Anagrams in a String: a fixed-size sliding window over
s, the length ofp. Add the entering character, remove the leaving one, compare the two 26-count arrays. Comparing 26 numbers is O(1), so the whole scan is O(n). Sliding Window covered the variable-size version; this is the fixed-size one.
Press Run (⌘ Enter) to see what happens.Ask about the alphabet before you code. If input can be any Unicode text, a 26-slot array is wrong, and a Counter (or a dict) is the safe signature: frozenset(Counter(w).items()) or a sorted tuple of its items.
Palindromes
Two tools cover almost every palindrome question.
Two pointers from the outside checks one string in O(n). Valid Palindrome II allows deleting at most one character. Walk inward until the first mismatch. One of those two characters must be the deleted one, so check whether the rest is a palindrome after skipping the left one or after skipping the right one. Two O(n) checks, so O(n) overall. The trap is greedily skipping only one side.
Press Run (⌘ Enter) to see what happens.Expand around the centre finds palindromic substrings. There are 2n - 1 centres (each character and each gap), and you grow outward from each while the ends match. Interval and Palindrome DP walks through the code for Longest Palindromic Substring and Palindromic Substrings, and contrasts it with the DP table for subsequences. It is O(n^2) worst case and O(1) space.
Manacher's algorithm finds the longest palindromic substring in O(n). It reuses the mirror image of palindromes already found, the same "do not redo work you already know" idea as KMP below. Know that it exists and what it costs. Interviewers almost never expect you to write it, and expand-around-centre is the accepted answer.
KMP: never move backwards in the text
The naive search tries every start position and compares up to m characters: O(n × m). On text like aaaaaaaab and pattern aaab it really does that much work, because each attempt matches almost the whole pattern before failing.
The Knuth-Morris-Pratt idea: when a mismatch happens after matching k characters, you already know those k text characters (they equal the pattern's first k). So you never re-read them. Instead you slide the pattern to the longest position where its start still lines up with what you just matched. That shift depends only on the pattern, so you precompute it once.
The prefix function (often called the LPS array, for "longest proper prefix which is also a suffix") stores, for each position i, the length of the longest proper prefix of p[:i+1] that is also a suffix of it. Such a prefix-suffix is called a border. For abcab, the border at the end is ab, so lps[4] = 2.
lps[0] is always 0: a single character has no proper border. k is the length of the prefix matched so far.
Why is it O(m) when there is a while loop inside a for? k goes up by at most 1 per step and every fall-back makes it strictly smaller. It cannot fall more times in total than it rose, so the total work across all iterations is at most 2m. The same argument makes the search O(n): i only moves forward through the text.
Press Run (⌘ Enter) to see what happens.Shortest Palindrome shows that the prefix function is a tool, not just a search algorithm. To make s a palindrome by adding characters to the front, find the longest prefix of s that is already a palindrome, then prepend the reverse of the rest. A prefix of s is a palindrome exactly when it equals a suffix of reverse(s). So build s + "#" + reverse(s): the last value of its prefix function is the longest prefix of s that matches a suffix of the reversed copy. The # separator (any character not in the input) stops a border from running across the middle.
What does this print?
print(prefix_function("abab"), prefix_function("aaaa"))Rabin-Karp: compare numbers, not strings
Rabin-Karp turns each window of the text into a number (a hash) and compares numbers. The trick is that the next window's hash comes from the previous one in O(1), by removing the character that leaves and adding the one that enters. That is a rolling hash.
Think of the string as digits in some base. With base 10 and digit strings it is ordinary arithmetic:
Hash the first 4 digits: 3141. Not equal to 1592, so this window cannot match. No character comparison needed.
Real strings use a larger base (256, or a prime such as 131) and take everything mod a large prime so the numbers stay small. Two pieces need care:
- Removing the leading character subtracts
char × base^(m-1). Precompute that weight withpow(base, m - 1, mod). In Python%always returns a non-negative result, so(h - x) % modis safe. In JavaScript and Java,%can return a negative number, so addmodbefore taking the remainder. In JavaScript also keep every intermediate product below 2^53, or useBigInt, or the hash silently loses precision. - Collisions: different strings can share a hash. Either verify every hash match by comparing the actual characters (always correct, and the expected cost stays O(n + m) with a good modulus), or use a double hash with two moduli, which makes a false match very unlikely without verifying. Verification is the safe default. Skipping it is a correctness bug that only appears on unlucky inputs, which is the worst kind.
Press Run (⌘ Enter) to see what happens.The tests with mod=3 are deliberate: with a tiny modulus almost every window collides, and the search is still correct because it verifies. That is how you prove to yourself the verification works.
Repeated DNA Sequences has a four-letter alphabet, so each letter fits in 2 bits and a 10-letter window fits in 20 bits exactly. The rolling "hash" is the window itself, with no collisions at all. Shift left by 2, OR in the new letter, and mask off the bits that fell out. (A set of 10-character substrings also passes, at O(10n) and more memory. Say both.)
Longest Duplicate Substring is where rolling hashes are the main tool. If some substring of length L repeats, so does a substring of every shorter length, so the answer is monotonic in L and you can binary search on L. For each candidate L, roll a hash across all windows of that length and look for a repeat. That is O(n log n) expected time.
Press Run (⌘ Enter) to see what happens.This version rolls the hash differently: it adds the new character first, then removes the one that is now length places back, with weight base^length. Both orders are correct as long as the weight matches. Getting that exponent off by one is the most common rolling-hash bug, which is why the block checks against a brute force. The overlapping repeat in banana (ana at 1 and 3) is allowed.
Z-function, built-ins, and what to use at work
The Z-function, briefly
z[i] is the length of the longest substring starting at i that matches a prefix of the whole string. Like KMP it is built in O(n) by reusing a window of an earlier match. To search, compute it on pattern + "$" + text: every position where z equals the pattern length is a match. It answers the same questions as the prefix function, and some people find it easier to reason about. Know one of the two well.
def z_function(s):
n = len(s)
z = [0] * n
l = r = 0 # [l, r) is the rightmost match window so far
for i in range(1, n):
if i < r:
z[i] = min(r - i, z[i - l]) # reuse the copy inside the window
while i + z[i] < n and s[z[i]] == s[i + z[i]]:
z[i] += 1
if i + z[i] > r:
l, r = i, i + z[i]
return zIn interviews, using text.find(pat), pat in text or JavaScript's text.indexOf(pat) is fine unless the question is to implement matching. Say so: "I'll use the built-in, which is well optimised; if you want, I can implement KMP." CPython's search is tuned, and since Python 3.10 it switches to the two-way algorithm for longer patterns, which keeps its worst case linear. JavaScript engines choose their own algorithm. At work, the built-in is always the first choice.
Where these algorithms show up on the job is indirect: rolling hashes power content-defined chunking in backup and sync tools (split a file where the rolling hash of the last few bytes hits a pattern, so an insertion only changes nearby chunks), and near-duplicate detection. Fast search tools such as grep use related skip-ahead ideas for plain substrings. Knowing that a plain substring search has a linear worst case also helps you spot when a slow search is really a regex problem rather than a string-size problem.
Unicode: what does "length" mean?
Your string code is only correct for the characters you tested. Three different things are called "a character":
- Code units: what the encoding stores. JavaScript, Java and C# strings are sequences of UTF-16 code units, and
.lengthcounts those. - Code points: Unicode's numbered characters. Python's
stris a sequence of code points, andlencounts those. - Grapheme clusters: what a person sees as one character. An
efollowed by a combining accent is two code points but one visible letter. Many emoji (flags, skin tones, family sequences) are several code points joined together.
Any emoji outside the Basic Multilingual Plane, such as U+1F600, needs two UTF-16 code units (a surrogate pair). So in JavaScript its .length is 2, s.split("") cuts it into two broken halves, and reversing with split("").reverse().join("") produces garbage. Array.from(s), the spread [...s] and for...of iterate by code point, which fixes surrogate pairs but still splits combining sequences.
Press Run (⌘ Enter) to see what happens.The same character can also be stored two ways: a precomposed é (one code point) or e plus a combining accent (two). They look identical and compare unequal. Normalise (NFC is the usual choice) before comparing or hashing user input: s.normalize("NFC") in JavaScript, unicodedata.normalize("NFC", s) in Python. For counting what users see, use a grapheme-aware tool such as Intl.Segmenter in JavaScript. Python's standard library has long lacked a grapheme segmenter, so check the docs for your Python version, or use the third-party package your team already relies on.
In interviews, the useful move is to ask: "Is the input ASCII, lowercase letters only, or arbitrary Unicode?" It decides whether a 26-slot array is valid, and it shows you have shipped string code to real users.
What does this print?
const s = "a\u{1F600}b";
console.log(s.length, [...s].length);Match each problem to the technique that fits it best.
- immutable string
- A string that cannot change in place. Every edit builds a new one, so += in a loop can be O(n^2).
- border
- A proper prefix of a string that is also a suffix of it. 'ab' is a border of 'abcab'.
- prefix function (LPS)
- lps[i] is the length of the longest border of p[:i+1]. KMP's precomputed table, built in O(m).
- rolling hash
- A hash of a sliding window updated in O(1) by removing the leaving character and adding the entering one.
- hash collision
- Two different strings with the same hash. Handle it by verifying the characters or by double hashing.
- code point
- One numbered Unicode character. Python len counts these; JavaScript .length counts UTF-16 code units.
- normalisation
- Converting text to one canonical form (usually NFC) so visually identical strings compare equal.