PDSA Interactive Book
Week 10

String / Pattern Matching

Finding a needle in a very long haystack, without looking at every straw twice.

After this chapter you can…
  • compare brute force, Boyer–Moore and KMP on the same input
  • compute a KMP failure function by hand
  • explain why KMP is O(n + m)
  • build and query a trie

The pattern-matching problem

Given a text T of length n and a pattern P of length m, find every position where P occurs in T. This is what Ctrl+F, grep, DNA search and plagiarism detectors do all day — often on texts with billions of characters, so efficiency matters.

Notation

T[i:i+m] == P means the pattern occurs at shift i. There are n − m + 1 possible shifts.

Brute force: try every shift

Line up the pattern at every shift and compare character by character, stopping at the first mismatch. Simple, no preparation, but the pattern can be compared almost fully before failing.

Python · editable
Expected output: ([0, 2, 7, 14, 16], 36) ([], 110)
String matching — brute forceInteractive
Worst case: O(n·m)

For T = aaaa…a and P = aaa…ab every shift matches almost all of P before failing on the last character. Natural English text is kinder, but DNA (alphabet of 4 letters) can be nasty.

Check yourself

How many shifts must brute force try for a text of length 100 and a pattern of length 10?

Boyer–Moore: skip ahead using the mismatch

Boyer–Moore compares the pattern from right to left and uses what it learns at a mismatch to skip several shifts at once. The bad-character rule: if the text character c that caused the mismatch does not appear in the pattern at all, the pattern can jump completely past it. If c appears in P, shift the pattern so its rightmost occurrence of c lines up with the text character.

Python · editable
Expected output: ([0, 2, 7, 14, 16], 42) ([36], 15)
Boyer–Moore (bad-character rule)Interactive

With a good alphabet size the average case is sub-linear — roughly n/m comparisons, since most shifts jump by nearly m. The worst case of the simple rule is still O(nm); the full algorithm adds a good-suffix rule for O(n + m).

Check yourself

In Boyer–Moore, a mismatch occurs at a text character that does not occur in the pattern anywhere. The pattern can…

Check yourself

Which statements describe Boyer–Moore?

Knuth–Morris–Pratt: never move backwards in the text

Brute force wastes the information gained from partial matches. Suppose we matched abab of the pattern ababc and then failed. We know the last text characters are abab. The longest prefix of the pattern that is also a suffix of abab is ab — so the next candidate alignment already has ab matched; there is no need to re-read those text characters.

Failure function (prefix function)

fail[j] = length of the longest proper prefix of P[0:j+1] that is also a suffix of it. It depends only on the pattern and tells us how far to fall back after a mismatch at position j + 1.

Python · editable
Expected output: [0, 0, 1, 2, 0, 1, 2, 3, 4] [0, 1, 2, 3] [0, 0, 0, 0]
Build a failure function — type any patternInteractive
Python · editable
Expected output: ([0, 2, 7, 14, 16], 22) ([], 31)
Knuth–Morris–PrattInteractive
Running time: O(n + m)

The pointer i into the text only moves forward. The value k increases at most once per text character and every fall-back decreases it, so the total number of fall-backs is at most n. Building the failure function is O(m) by the same argument.

AlgorithmPreprocessingWorst-case matchingTypical
Brute forcenoneO(nm)fine for short texts
Boyer–MooreO(m + alphabet)O(nm) simple rule / O(n+m) fullsub-linear, often the fastest in practice
KMPO(m)O(n + m)guaranteed linear, never re-reads text
Predict the output

What is the KMP failure array for 'aabaaab'?

def failure(P):
    fail, k = [0] * len(P), 0
    for j in range(1, len(P)):
        while k > 0 and P[j] != P[k]:
            k = fail[k - 1]
        if P[j] == P[k]:
            k += 1
        fail[j] = k
    return fail
print(failure("aabaaab"))
Check yourself

What does fail[j] store in KMP?

Check yourself

Why is KMP's total matching time O(n + m) and not O(nm)?

Tries: searching many words at once

A trie (retrieval tree, pronounced 'try') stores a set of words in a tree where each edge is labelled by a letter and the path from the root spells a prefix. Words that share a prefix share a path. Lookup of a word of length L takes O(L) — independent of how many words are stored.

Trie — add words and look for themInteractive
Python · editable
Expected output: True False ['car', 'card', 'care'] ['dog', 'done']
Where tries shine

Autocomplete, spell-checking, IP routing tables, T9 keyboards. The shared prefixes also save memory when many words begin alike. A suffix trie of the text (all suffixes inserted) lets you test whether any pattern occurs in the text in O(m).

Check yourself

How long does it take to check whether a word of length 7 is in a trie holding a million words?

Predict the output

How many nodes (excluding the root) does a trie of these words have?

words = ["to", "tea", "ted", "ten", "in", "inn"]
nodes = set()
for w in words:
    for i in range(1, len(w) + 1):
        nodes.add(w[:i])
print(len(nodes))

Chapter challenge — Week 10

…
Check yourself

Which algorithm never moves its text pointer backwards?

Predict the output

How many character comparisons does brute force make?

T, P = "aaaaab", "aab"
count = 0
for i in range(len(T) - len(P) + 1):
    for j in range(len(P)):
        count += 1
        if T[i + j] != P[j]:
            break
print(count)
Check yourself

Pattern 'abcab' — what is the last entry of its KMP failure array?

Put in order

KMP matching loop (for each text character).

Check yourself

Choose the true statements.

Check yourself

Searching for pattern P of length m: the number of candidate shifts in text of length n is…

Check yourself

For which scenario is a trie the most natural tool?

Practice on LeetCode

String matching and tries.

How to practise

Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.

0 / 11 solvedTick a problem when you have solved it — saved in this browser.
ProblemLevelPractises
Find the Index of the First Occurrence in a String ↗Easybrute force, then KMP
Repeated Substring Pattern ↗Easyfailure-function idea
Longest Happy Prefix ↗Hardexactly the KMP failure function
Shortest Palindrome ↗HardKMP on s + '#' + reverse(s)
Repeated String Match ↗Mediumpattern search on a repeated text
Longest Common Prefix ↗Easyprefix thinking before tries
Implement Trie (Prefix Tree) ↗Mediumbuild a trie
Design Add and Search Words Data Structure ↗Mediumtrie + DFS for wildcards
Replace Words ↗Mediumshortest-prefix lookup in a trie
Search Suggestions System ↗Mediumautocomplete
Word Search II ↗Hardtrie + backtracking on a grid

Key takeaways

  • Pattern matching asks where a pattern of length m occurs in a text of length n. Brute force is O(nm).
  • Boyer–Moore compares right to left and uses the bad-character rule to skip ahead — typically sub-linear.
  • KMP precomputes a failure function in O(m) and then scans the text in O(n) with no backtracking.
  • Tries index many words by their prefixes: lookup in O(word length), natural for autocomplete.

PDSA Interactive Book · Programming, Data Structures and Algorithms using Python (BSCS2002), IIT Madras BS Degree Programme.
Created by Ammar Hashmi · © 2026. An unofficial study companion — the syllabus follows the official course page and the examples are built around the PDSA Online Textbook; lectures by Prof. Madhavan Mukund (CMI). Always cross-check with the official course material.
Found a mistake or have a suggestion? Report it on GitHub ↗ · Press / to search.