Skip to content

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.

28 min read0/5 questions

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.

Quick check
A function checks whether a string is a palindrome with: if len(s) < 2 return True; return s[0] == s[-1] and is_pal(s[1:-1]). What is its time complexity on a palindrome of length n?
Need a nudge? A hint rules out a wrong answer.

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 of p. 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.
Python
def find_anagrams(s, p): if len(p) > len(s): return [] need = [0] * 26 have = [0] * 26 for ch in p: need[ord(ch) - 97] += 1 out = [] for i, ch in enumerate(s): have[ord(ch) - 97] += 1 # character entering the window if i >= len(p): have[ord(s[i - len(p)]) - 97] -= 1 # character leaving the window if have == need: # 26 comparisons: O(1) out.append(i - len(p) + 1) return out def group_anagrams(words): groups = {} for w in words: key = [0] * 26 for ch in w: key[ord(ch) - 97] += 1 groups.setdefault(tuple(key), []).append(w) # lists cannot be dict keys; tuples can return list(groups.values()) assert find_anagrams("cbaebabacd", "abc") == [0, 6]assert find_anagrams("abab", "ab") == [0, 1, 2]assert find_anagrams("a", "ab") == []assert sorted(map(sorted, group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))) == [["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]print(find_anagrams("cbaebabacd", "abc"))
Output
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.

Python
def valid_palindrome_ii(s): def is_pal(lo, hi): while lo < hi: if s[lo] != s[hi]: return False lo += 1 hi -= 1 return True lo, hi = 0, len(s) - 1 while lo < hi: if s[lo] != s[hi]: # first mismatch: one of these two must be the deleted character return is_pal(lo + 1, hi) or is_pal(lo, hi - 1) lo += 1 hi -= 1 return True assert valid_palindrome_ii("aba")assert valid_palindrome_ii("abca") # delete b or cassert not valid_palindrome_ii("abc")assert valid_palindrome_ii("deeee")assert valid_palindrome_ii("ebcbbececabbacecbbcbe")assert valid_palindrome_ii("")print(valid_palindrome_ii("abca"), valid_palindrome_ii("abc"))
Output
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.

Building the prefix function for aabaaab
a
0
↑k
a
1
↑i
b
2
a
3
a
4
a
5
b
6
lps = [0, ., ., ., ., ., .]

lps[0] is always 0: a single character has no proper border. k is the length of the prefix matched so far.

1/6

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.

Python
def prefix_function(p): """lps[i] = length of the longest proper prefix of p[:i+1] that is also a suffix of it.""" lps = [0] * len(p) k = 0 # length of the current matched prefix for i in range(1, len(p)): while k > 0 and p[i] != p[k]: k = lps[k - 1] # fall back to the next shorter border if p[i] == p[k]: k += 1 lps[i] = k return lps def kmp_search(text, pat): if not pat: return 0 lps = prefix_function(pat) k = 0 for i, ch in enumerate(text): while k > 0 and ch != pat[k]: k = lps[k - 1] # reuse what already matched; i never moves back if ch == pat[k]: k += 1 if k == len(pat): return i - len(pat) + 1 return -1 def shortest_palindrome(s): """Fewest characters added to the FRONT to make s a palindrome.""" combined = s + "#" + s[::-1] # '#' stops a border running past the middle keep = prefix_function(combined)[-1] # longest palindromic prefix of s return s[keep:][::-1] + s assert prefix_function("aabaaab") == [0, 1, 0, 1, 2, 2, 3]assert prefix_function("abcab") == [0, 0, 0, 1, 2]assert kmp_search("sadbutsad", "sad") == 0assert kmp_search("leetcode", "leeto") == -1assert kmp_search("aabaabaaab", "aabaaab") == 3assert all(kmp_search(t, p) == t.find(p) for t in ["abababc", "aaaa", "xyz"] for p in ["abc", "aa", "z", "q"])assert shortest_palindrome("aacecaaa") == "aaacecaaa"assert shortest_palindrome("abcd") == "dcbabcd"assert shortest_palindrome("") == ""print(prefix_function("aabaaab"), kmp_search("aabaabaaab", "aabaaab"))
Output
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.

Predict the outputPython

What does this print?

print(prefix_function("abab"), prefix_function("aaaa"))
Need a nudge? Hints walk you through it.

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:

Rolling a base-10 hash: find 1592 in 31415926
3
0
1
1
4
2
1
3
5
4
9
5
2
6
6
7
window = 3141target = 1592

Hash the first 4 digits: 3141. Not equal to 1592, so this window cannot match. No character comparison needed.

1/4

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 with pow(base, m - 1, mod). In Python % always returns a non-negative result, so (h - x) % mod is safe. In JavaScript and Java, % can return a negative number, so add mod before taking the remainder. In JavaScript also keep every intermediate product below 2^53, or use BigInt, 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.
Python
def rabin_karp(text, pat, base=256, mod=1_000_000_007): m, n = len(pat), len(text) if m == 0: return 0 if m > n: return -1 high = pow(base, m - 1, mod) # weight of the leading character hp = hw = 0 for i in range(m): hp = (hp * base + ord(pat[i])) % mod hw = (hw * base + ord(text[i])) % mod for start in range(n - m + 1): if hw == hp and text[start:start + m] == pat: # verify: equal hashes may be a collision return start if start + m < n: hw = (hw - ord(text[start]) * high) % mod # drop the leading char (Python % is never negative) hw = (hw * base + ord(text[start + m])) % mod # shift and add the new char return -1 def repeated_dna(s): seen, repeated = set(), set() code = {"A": 0, "C": 1, "G": 2, "T": 3} window, mask = 0, (1 << 20) - 1 # 10 letters x 2 bits: an exact hash, no collisions for i, ch in enumerate(s): window = ((window << 2) | code[ch]) & mask if i >= 9: if window in seen: repeated.add(s[i - 9:i + 1]) seen.add(window) return sorted(repeated) assert rabin_karp("31415926", "1592") == 3assert rabin_karp("hello world", "world") == 6assert rabin_karp("aaaa", "b") == -1assert all(rabin_karp(t, p) == t.find(p) for t in ["abababc", "aaaa", "xyz"] for p in ["abc", "aa", "z", "q"])assert rabin_karp("abc", "abc", base=2, mod=3) == 0 # tiny mod: collisions everywhere, still correctassert rabin_karp("bcaabc", "abc", base=2, mod=3) == 3assert repeated_dna("AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT") == ["AAAAACCCCC", "CCCCCAAAAA"]assert repeated_dna("AAAAAAAAAAAAA") == ["AAAAAAAAAA"]print(rabin_karp("31415926", "1592"), repeated_dna("AAAAAAAAAAAAA"))
Output
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.

Python
def longest_dup_substring(s): n = len(s) MOD1, MOD2, BASE = 1_000_000_007, 998_244_353, 131 def find_repeat(length): """Return the start of a substring of this length that occurs twice, or -1.""" if length == 0: return 0 p1, p2 = pow(BASE, length, MOD1), pow(BASE, length, MOD2) h1 = h2 = 0 seen = {} for i, ch in enumerate(s): c = ord(ch) h1 = (h1 * BASE + c) % MOD1 h2 = (h2 * BASE + c) % MOD2 if i >= length: # remove the char that left the window old = ord(s[i - length]) h1 = (h1 - old * p1) % MOD1 h2 = (h2 - old * p2) % MOD2 if i >= length - 1: start = i - length + 1 key = (h1, h2) # double hash: a false match is very unlikely if key in seen: first = seen[key] if s[first:first + length] == s[start:start + length]: return start else: seen[key] = start return -1 lo, hi, best = 1, n - 1, "" while lo <= hi: # longer repeats imply shorter ones: binary search mid = (lo + hi) // 2 start = find_repeat(mid) if start >= 0: best = s[start:start + mid] lo = mid + 1 else: hi = mid - 1 return best def brute(s): best = "" for i in range(len(s)): for j in range(i + 1, len(s) + 1): if j - i > len(best) and s.find(s[i:j], i + 1) != -1: best = s[i:j] return best assert longest_dup_substring("banana") == "ana"assert longest_dup_substring("abcd") == ""assert longest_dup_substring("aaaaa") == "aaaa"for t in ["mississippi", "abcabcabc", "xyzzyx", "aabbaabb"]: assert len(longest_dup_substring(t)) == len(brute(t)), tprint(longest_dup_substring("banana"), longest_dup_substring("mississippi"))
Output
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.

Quick check
Your Rabin-Karp search returns the window's index as soon as the window hash equals the pattern hash. What is wrong?
Need a nudge? A hint rules out a wrong answer.

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 z

In 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 .length counts those.
  • Code points: Unicode's numbered characters. Python's str is a sequence of code points, and len counts those.
  • Grapheme clusters: what a person sees as one character. An e followed 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.

JavaScript
const smile = "\u{1F600}"; // one emoji, outside the Basic Multilingual Planeconsole.log(smile.length); // UTF-16 code unitsconsole.log(Array.from(smile).length); // code pointsconsole.log(smile.split("").length); // split("") cuts it into two broken halvesconst accented = "e\u0301"; // e + combining acute accent: looks like one letterconsole.log(accented.length, accented.normalize("NFC").length);console.log([...("ab" + smile)].reverse().join("") === smile + "ba");
Output
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.

Predict the outputJavaScript

What does this print?

const s = "a\u{1F600}b";
console.log(s.length, [...s].length);
Need a nudge? Hints walk you through it.
Match the pairs0/5 matched

Match each problem to the technique that fits it best.

Choose an item, then its match on the other side.
Key terms
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.