STOP 03 · LINEAR STRUCTURES
String Parsing and Matching
KMP prefix function O(n + m) time · O(m) space
- Learn first
- Leads to
- How often asked
- asked by 6 companies · in 7 reportsDoorDash 2, Airbnb 1, Akuna Capital 1, Carvana 1, Meta 1
Warm up with this one
LC 344Reverse StringStuck? Peek at the approach
Reverse characters in place with two pointers, making interval conventions and stopping conditions explicit.
Key points
- pi[i] is the length of the longest proper prefix of pat[0..i] that is also its suffix; on a mismatch j falls back to pi[j-1] and the text pointer never moves back.
- Building pi and scanning the text are the same loop: building the table is the pattern matching against itself.
- For parsing tasks, advance one index by hand over digits, signs and brackets; edge cases are easier than with split.
Common pitfalls
- After a full match set j = pi[j-1]; otherwise you miss overlapping occurrences ("aa" occurs 3 times in "aaaa").
- Concatenating strings with + in a loop is O(n²); collect pieces and join in Python, use StringBuilder in Java.
- In Go, s[i] is a byte and len(s) counts bytes; convert to []rune for multi-byte text such as Chinese.
Watch it run
Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.
KMP · prefix function and linear matching
Find every occurrence of "abcaby" in "abxabcabcaby"
Try your own input
- Phase
- Prefix function
- Matches at
- —
First the pattern "abcaby" alone: pi[i] is the longest proper prefix of its first i+1 characters that is also a suffix.
Invariantj is the matched length; on a mismatch it falls to pi[j−1], the longest border of what matched, so no start is skipped.
Template
Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 344, with it.
Python
def find_all(text: str, pat: str) -> list[int]:
"""Start index of every occurrence of a non-empty pat in text."""
m = len(pat)
pi = [0] * m # pi[i]: longest proper prefix of pat[:i+1] that is also its suffix
j = 0
for i in range(1, m):
while j and pat[i] != pat[j]:
j = pi[j - 1]
if pat[i] == pat[j]:
j += 1
pi[i] = j
res, j = [], 0
for i, c in enumerate(text):
while j and c != pat[j]:
j = pi[j - 1]
if c == pat[j]:
j += 1
if j == m:
res.append(i - m + 1)
j = pi[j - 1] # keep going: matches may overlap
return resC++
// Start index of every occurrence of a non-empty pat in text.
vector<int> findAll(const string& text, const string& pat) {
int m = pat.size();
vector<int> pi(m, 0); // pi[i]: longest proper border of pat[0..i]
for (int i = 1, j = 0; i < m; i++) {
while (j && pat[i] != pat[j]) j = pi[j - 1];
if (pat[i] == pat[j]) j++;
pi[i] = j;
}
vector<int> res;
for (int i = 0, j = 0; i < (int)text.size(); i++) {
while (j && text[i] != pat[j]) j = pi[j - 1];
if (text[i] == pat[j]) j++;
if (j == m) {
res.push_back(i - m + 1);
j = pi[j - 1]; // keep going: matches may overlap
}
}
return res;
}Java
class Solution {
// Start index of every occurrence of a non-empty pat in text.
List<Integer> findAll(String text, String pat) {
int m = pat.length();
int[] pi = new int[m]; // pi[i]: longest proper border of pat[0..i]
for (int i = 1, j = 0; i < m; i++) {
while (j > 0 && pat.charAt(i) != pat.charAt(j)) j = pi[j - 1];
if (pat.charAt(i) == pat.charAt(j)) j++;
pi[i] = j;
}
List<Integer> res = new ArrayList<>();
for (int i = 0, j = 0; i < text.length(); i++) {
while (j > 0 && text.charAt(i) != pat.charAt(j)) j = pi[j - 1];
if (text.charAt(i) == pat.charAt(j)) j++;
if (j == m) {
res.add(i - m + 1);
j = pi[j - 1]; // keep going: matches may overlap
}
}
return res;
}
}Go
// findAll returns the start index of every occurrence of a non-empty pat in text.
func findAll(text, pat string) []int {
m := len(pat)
pi := make([]int, m) // pi[i]: longest proper border of pat[:i+1]
for i, j := 1, 0; i < m; i++ {
for j > 0 && pat[i] != pat[j] {
j = pi[j-1]
}
if pat[i] == pat[j] {
j++
}
pi[i] = j
}
var res []int
for i, j := 0, 0; i < len(text); i++ {
for j > 0 && text[i] != pat[j] {
j = pi[j-1]
}
if text[i] == pat[j] {
j++
}
if j == m {
res = append(res, i-m+1)
j = pi[j-1] // keep going: matches may overlap
}
}
return res
}Common variants
Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.
Rabin-Karp rolling hashExpected O(n + m) time · O(1) space
When many equal-length substrings must be compared quickly (repeated substrings, binary searching the length of the longest repeat, palindromic prefixes), use a polynomial hash: sliding the window drops the leaving character's share, multiplies by the base and adds the new one, all in O(1). Confirm a hash hit character by character, since collisions happen. LC 28, LC 1044 and LC 214 can use it.
Python
def rabin_karp(text: str, pat: str) -> list[int]:
"""Start of every occurrence of a non-empty pat, found with rolling hashes."""
MOD, BASE = 1_000_000_007, 131
n, m = len(text), len(pat)
if m > n:
return []
top = pow(BASE, m - 1, MOD) # weight of the character leaving the window
hp = hw = 0
for i in range(m):
hp = (hp * BASE + ord(pat[i])) % MOD
hw = (hw * BASE + ord(text[i])) % MOD
res = []
for i in range(n - m + 1):
if hw == hp and text[i : i + m] == pat: # confirm a hit: hashes can collide
res.append(i)
if i + m < n: # roll: drop text[i], add text[i + m]
hw = ((hw - ord(text[i]) * top) * BASE + ord(text[i + m])) % MOD
return resC++
// Start of every occurrence of a non-empty pat, found with rolling hashes.
vector<int> rabinKarp(const string& text, const string& pat) {
const long long MOD = 1000000007, BASE = 131;
int n = text.size(), m = pat.size();
if (m > n) return {};
long long top = 1, hp = 0, hw = 0; // top: weight of the character leaving the window
for (int i = 1; i < m; i++) top = top * BASE % MOD;
for (int i = 0; i < m; i++) {
hp = (hp * BASE + pat[i]) % MOD;
hw = (hw * BASE + text[i]) % MOD;
}
vector<int> res;
for (int i = 0; i + m <= n; i++) {
if (hw == hp && text.compare(i, m, pat) == 0) res.push_back(i); // confirm a hit: hashes can collide
if (i + m < n) // roll: drop text[i], add text[i + m]
hw = ((hw - text[i] * top % MOD + MOD) % MOD * BASE + text[i + m]) % MOD;
}
return res;
}Java
class Solution {
// Start of every occurrence of a non-empty pat, found with rolling hashes.
List<Integer> rabinKarp(String text, String pat) {
final long MOD = 1_000_000_007L, BASE = 131;
int n = text.length(), m = pat.length();
List<Integer> res = new ArrayList<>();
if (m > n) return res;
long top = 1, hp = 0, hw = 0; // top: weight of the character leaving the window
for (int i = 1; i < m; i++) top = top * BASE % MOD;
for (int i = 0; i < m; i++) {
hp = (hp * BASE + pat.charAt(i)) % MOD;
hw = (hw * BASE + text.charAt(i)) % MOD;
}
for (int i = 0; i + m <= n; i++) {
if (hw == hp && text.startsWith(pat, i)) res.add(i); // confirm a hit: hashes can collide
if (i + m < n) // roll: drop text[i], add text[i + m]
hw = ((hw - text.charAt(i) * top % MOD + MOD) % MOD * BASE + text.charAt(i + m)) % MOD;
}
return res;
}
}Go
// rabinKarp returns the start of every occurrence of a non-empty pat, found with rolling hashes.
func rabinKarp(text, pat string) []int {
const mod, base = 1_000_000_007, 131
n, m := len(text), len(pat)
res := []int{}
if m > n {
return res
}
top, hp, hw := 1, 0, 0 // top: weight of the character leaving the window
for i := 1; i < m; i++ {
top = top * base % mod
}
for i := 0; i < m; i++ {
hp = (hp*base + int(pat[i])) % mod
hw = (hw*base + int(text[i])) % mod
}
for i := 0; i+m <= n; i++ {
if hw == hp && text[i:i+m] == pat { // confirm a hit: hashes can collide
res = append(res, i)
}
if i+m < n { // roll: drop text[i], add text[i + m]
hw = ((hw-int(text[i])*top%mod+mod)%mod*base + int(text[i+m])) % mod
}
}
return res
}Reverse the whole, then each wordO(n) time · O(1) space (a char list in Python, whose strings are immutable)
When word order must change in place (O(1) extra space): squeeze out extra spaces with read and write pointers, reverse each word, then reverse everything once, which flips the word order while turning each word the right way round again. LC 151 (Reverse Words in a String); LC 344, LC 345 and LC 917 are the two-pointer reversal inside it.
Python
def reverse_words(s: str) -> str:
"""Words in reverse order, single spaces between them, none at the ends."""
chars = list(s)
def reverse(i: int, j: int) -> None: # chars[i..j] in place
while i < j:
chars[i], chars[j] = chars[j], chars[i]
i, j = i + 1, j - 1
w = i = 0 # w writes, i reads; chars[:w] is the squeezed result so far
while i < len(chars):
if chars[i] == " ":
i += 1
continue
if w:
chars[w] = " " # one space before every word but the first
w += 1
start = w
while i < len(chars) and chars[i] != " ":
chars[w] = chars[i]
w, i = w + 1, i + 1
reverse(start, w - 1) # each word backwards now...
reverse(0, w - 1) # ...so reversing it all leaves the words in reverse order, each readable
return "".join(chars[:w])C++
// Words in reverse order, single spaces between them, none at the ends.
string reverseWords(string s) {
int w = 0; // s[0, w) is the squeezed result so far
for (int i = 0; i < (int)s.size();) {
if (s[i] == ' ') {
i++;
continue;
}
if (w) s[w++] = ' '; // one space before every word but the first
int start = w;
while (i < (int)s.size() && s[i] != ' ') s[w++] = s[i++];
reverse(s.begin() + start, s.begin() + w); // each word backwards now...
}
s.resize(w);
reverse(s.begin(), s.end()); // ...so reversing it all leaves the words in reverse order, each readable
return s;
}Java
class Solution {
// Words in reverse order, single spaces between them, none at the ends.
String reverseWords(String text) {
char[] s = text.toCharArray();
int w = 0; // s[0, w) is the squeezed result so far
for (int i = 0; i < s.length;) {
if (s[i] == ' ') {
i++;
continue;
}
if (w > 0) s[w++] = ' '; // one space before every word but the first
int start = w;
while (i < s.length && s[i] != ' ') s[w++] = s[i++];
reverse(s, start, w - 1); // each word backwards now...
}
reverse(s, 0, w - 1); // ...so reversing it all leaves the words in reverse order, each readable
return new String(s, 0, w);
}
private void reverse(char[] s, int i, int j) {
for (; i < j; i++, j--) {
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
}Go
// reverseWords returns the words in reverse order, single spaces between them, none at the ends.
func reverseWords(text string) string {
s := []byte(text)
reverse := func(i, j int) { // s[i..j] in place
for ; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}
w := 0 // s[:w] is the squeezed result so far
for i := 0; i < len(s); {
if s[i] == ' ' {
i++
continue
}
if w > 0 {
s[w] = ' ' // one space before every word but the first
w++
}
start := w
for i < len(s) && s[i] != ' ' {
s[w] = s[i]
w, i = w+1, i+1
}
reverse(start, w-1) // each word backwards now...
}
reverse(0, w-1) // ...so reversing it all leaves the words in reverse order, each readable
return string(s[:w])
}Why it works
- On a mismatch it is safe to move only j and never the text pointer: any earlier start that could still match corresponds to a proper prefix of the matched part that is also its suffix, and pi gives the longest such border, so falling back along pi skips no possible start.
- Linear time comes from a potential argument: j grows by at most 1 per step, every fallback shrinks it by at least 1, and j never goes below 0, so total fallbacks are bounded by total advances, O(n + m) overall.
Say it in 30 seconds
When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.
KMP 的核心是前缀函数 pi,pi[i] 表示模式串前 i+1 个字符里,既是真前缀又是后缀的最长长度。匹配时文本指针从不后退,失配就把模式指针跳到 pi[j−1],因为能继续匹配的起点只可能对应这些前后缀相等的长度。模式指针每步最多加一、回退总量不超过前进总量,所以整体是 O(n + m)。建表本身就是模式串和自己匹配。KMP rests on the prefix function: pi[i] is the length of the longest proper prefix of the first i + 1 pattern characters that is also a suffix. During matching the text pointer never moves back; on a mismatch the pattern pointer jumps to pi[j − 1], because any start that can still match corresponds to one of those borders. The pattern pointer rises by at most one per step and can only fall as much as it rose, so the whole thing is O(n + m). Building the table is the pattern matching against itself.Grade yourself
Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.
Quick quiz
4 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice
Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.
Template drills
Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.
These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.
def find_all(text: str, pat: str) -> list[int]:
"""Start index of every occurrence of a non-empty pat in text."""
m = len(pat)
pi = [0] * m
j = 0
for i in range(1, m): res.append(i - m + 1)
j = pi[j - 1]
return resPractice by stage
This stop's 20 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.
Foundation 4
| # | Problem | Approach | Rating |
|---|---|---|---|
| 344 | Reverse String | Reverse characters in place with two pointers, making interval conventions and stopping conditions explicit. | |
| 345 | Reverse Vowels of a String | Skip nontarget characters from both ends and reverse only the vowel subsequence. | |
| 917 | Reverse Only Letters | Reverse letters while preserving nonletter positions, paying attention to character classification. | |
| 796 | Rotate String | Reduce rotation to matching within a concatenated string, while also checking the lengths. |
Core 11
| # | Problem | Approach | Rating |
|---|---|---|---|
| 151 | Reverse Words in a String | Separate word tokenization, whitespace normalization, and word-order reversal. | |
| 8 | String to Integer (atoi) | Organize whitespace, sign, consecutive digits, and overflow handling into a clear parsing process. | |
| 273 | Integer to English Words | Convert numbers to English in groups of thousands, handling zero and spacing between groups. | |
| 28 | Find the Index of the First Occurrence in a String | Derive the prefix function from naive matching and explain how a mismatch reuses already matched information. | |
| 459 | Repeated Substring Pattern | Detect repeated substrings through periodic structure or the prefix function instead of checking only the endpoints. | |
| 686 | Repeated String Match | Bound the number of repetitions needed, then match the pattern across repetition boundaries. | |
| 1023 | Camelcase Matching | Advance the pattern pointer only on a match and reject extra uppercase letters that cannot be skipped. | |
| 809 | Expressive Words | Align character runs and check whether each run length satisfies the stretching rules. | |
| 1750 | Minimum Length of String After Deleting Similar Ends | Remove whole matching character runs from both ends, handling termination when all characters are identical. | |
| 1328 | Break a Palindrome | Find the first position that can make a palindrome lexicographically smaller, with a fallback position that makes it larger. | |
| 1763 | Longest Nice Substring | Enumerate candidates and verify paired uppercase and lowercase letters; discuss how divide and conquer can narrow the search. |
Advanced 5
| # | Problem | Approach | Rating |
|---|---|---|---|
| 65 | Valid Number | Recognize valid numbers with decimal points and exponents using a finite-state machine or explicit grammar branches. | |
| 68 | Text Justification | Pack words greedily by line and distribute spaces, treating the last line and single-word lines separately. | |
| 214 | Shortest Palindrome | Reduce the shortest palindrome formed by prepending characters to finding the longest palindromic prefix through string matching. | |
| 1044 | Longest Duplicate Substring | Binary-search the repeated-substring length using substring hashes, and discuss collisions and verification. | |
| 336 | Palindrome Pairs | Enumerate word split points and look up reversed complements, handling empty strings and palindromic suffixes. |
OA questions on this topic 213
- Subarray Matches a Comparison PatternMeta
- Cyclic Vowel ShiftMeta
- Compute Difference Between Uppercase and Lowercase LettersMeta
- Replace Every Nth ConsonantMeta
- Buses in a Bustling TownMeta
- Find How Many Subarrays Match The PatternMeta
- Find Longest RegexAmazon
- Find Similarities (Password Subsequence)Amazon
- Count Valid SplitsAmazon
- Get Minimum String (Box Lex-Smallest)Amazon
Core Skills
Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.
- KMP String MatchingMedium