cswork / templatesOpen the Line 500 list

STOP 03 · LINEAR STRUCTURES

String Parsing and Matching

KMP prefix function O(n + m) time · O(m) space

Contest ratings Rating 1167–Rating 2429· median Rating 1512(8 of 20 problems rated by zerotrac)

Open the Line 500 list · stop 03 · 20 problems
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 StringEasy
Stuck? Peek at the approach

Reverse characters in place with two pointers, making interval conventions and stopping conditions explicit.

Key points

  1. 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.
  2. Building pi and scanning the text are the same loop: building the table is the pattern matching against itself.
  3. 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.

Interactive demo · step by step

KMP · prefix function and linear matching

Find every occurrence of "abcaby" in "abxabcabcaby"

Try your own input
a0
b1
x2
a3
b4
c5
a6
b7
c8
a9
b10
y11
ap0
bp1
cp2
ap3
bp4
yp5
·pi0
·pi1
·pi2
·pi3
·pi4
·pi5
CurrentDiscovered / computedAnswer
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 res
C++
// 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 res
C++
// 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

  1. 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.
  2. 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)。建表本身就是模式串和自己匹配。
English
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.

Key points you covered (0 of 2)
How well did you know it?

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

4 questions
  1. When building a long string in Python, why collect the pieces in a list and call "".join(parts) instead of doing s += part in a loop?
  2. Two lowercase strings of length n are checked for being anagrams with a 26-slot count array. Time and extra space?
  3. What is the time complexity when s is a palindrome (n = len(s))?
    def is_pal(s):
        if len(s) <= 1:
            return True
        return s[0] == s[-1] and is_pal(s[1:-1])
  4. What is the time complexity of this Java method?
    static String repeatX(int n) {
        String s = "";
        for (int i = 0; i < n; i++) {
            s += "x";
        }
        return s;
    }

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 res

Practice 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

#ProblemApproachRating
344Reverse StringReverse characters in place with two pointers, making interval conventions and stopping conditions explicit.
345Reverse Vowels of a StringSkip nontarget characters from both ends and reverse only the vowel subsequence.
917Reverse Only LettersReverse letters while preserving nonletter positions, paying attention to character classification.Rating 1229
796Rotate StringReduce rotation to matching within a concatenated string, while also checking the lengths.Rating 1167

Core 11

#ProblemApproachRating
151Reverse Words in a StringSeparate word tokenization, whitespace normalization, and word-order reversal.
8String to Integer (atoi)Organize whitespace, sign, consecutive digits, and overflow handling into a clear parsing process.
273Integer to English WordsConvert numbers to English in groups of thousands, handling zero and spacing between groups.
28Find the Index of the First Occurrence in a StringDerive the prefix function from naive matching and explain how a mismatch reuses already matched information.
459Repeated Substring PatternDetect repeated substrings through periodic structure or the prefix function instead of checking only the endpoints.
686Repeated String MatchBound the number of repetitions needed, then match the pattern across repetition boundaries.
1023Camelcase MatchingAdvance the pattern pointer only on a match and reject extra uppercase letters that cannot be skipped.Rating 1537
809Expressive WordsAlign character runs and check whether each run length satisfies the stretching rules.Rating 1605
1750Minimum Length of String After Deleting Similar EndsRemove whole matching character runs from both ends, handling termination when all characters are identical.Rating 1502
1328Break a PalindromeFind the first position that can make a palindrome lexicographically smaller, with a fallback position that makes it larger.Rating 1474
1763Longest Nice SubstringEnumerate candidates and verify paired uppercase and lowercase letters; discuss how divide and conquer can narrow the search.Rating 1522

Advanced 5

#ProblemApproachRating
65Valid NumberRecognize valid numbers with decimal points and exponents using a finite-state machine or explicit grammar branches.
68Text JustificationPack words greedily by line and distribute spaces, treating the last line and single-word lines separately.
214Shortest PalindromeReduce the shortest palindrome formed by prepending characters to finding the longest palindromic prefix through string matching.
1044Longest Duplicate SubstringBinary-search the repeated-substring length using substring hashes, and discuss collisions and verification.Rating 2429
336Palindrome PairsEnumerate word split points and look up reversed complements, handling empty strings and palindromic suffixes.

Core Skills

Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.