Skip to contentKEEP THE CRAFTTHE SANCTUARY

String Matching

Specify first or all occurrences, overlap, empty patterns and symbol equality before selecting a matcher. Contrast naive alignment scans, deterministic KMP reuse, and verified rolling-hash candidates.

1 practice exercise1 interview problem

Recognize it when The pattern must match consecutive symbols at some text alignment.

Checking your account…

String Matching Code Labs

Define Pattern Alignment and Match Semantics

String matching asks where a pattern aligns with consecutive text symbols. Define first versus all matches, overlapping behavior, case normalization, and the empty-pattern result before selecting an algorithm.

Reuse Information after a Mismatch

Naive matching advances one alignment and repeats comparisons. KMP reuses a prefix-suffix table, while Rabin-Karp reuses a rolling fingerprint and verifies candidates.

Trace Naive Pattern Alignments

Reference
def alignment_trace(text,pattern):
    if pattern=="":return [[0,0]]
    trace=[]
    for start in range(len(text)-len(pattern)+1):
        matched=0
        while matched<len(pattern) and text[start+matched]==pattern[matched]:matched+=1
        trace.append([start,matched])
        if matched==len(pattern):break
    return trace
Practice

Implement alignment_trace(text,pattern). Return [start,matched_prefix_length] for each alignment through the first full match. Empty pattern returns [[0,0]]; a pattern longer than text returns [].

Public tests

  • Measure each mismatch alignment

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Naive Pattern Alignments

def alignment_trace(text,pattern):
    if pattern=="":return [[0,0]]
    trace=[]
    for start in range(len(text)-len(pattern)+1):
        matched=0
        while matched<len(pattern) and text[start+matched]==pattern[matched]:matched+=1
        trace.append([start,matched])
        if matched==len(pattern):break
    return trace

Reject Earlier Alignments Before Returning a Match

Predict the matched-prefix length at each legal start in the existing Lab. It intentionally stops after the first full match, so the trace is not an all-occurrence output.

Step Executed statement State Why
Reset start zero matched=0 start=0, matched=0 Each naive alignment restarts its prefix comparison.
Compare at zero while matched<len(pattern) and text[start+matched]==pattern[matched]:matched+=1 after inner loop: matched=1 The first a agrees, then the next a mismatches pattern b.
Record zero trace.append([start,matched]) trace=[[0,1]] Recording happens after the comparison loop, not on every matched symbol.
Record start one trace.append([start,matched]) after its reset and comparison loop: trace=[[0,1],[1,1]] The next alignment repeats one a comparison before c mismatches b.
Record start two trace.append([start,matched]) after its reset and comparison loop: row=[2,0] c rejects this alignment on its first comparison.
Record complete alignment trace.append([start,matched]) after start 3 comparison loop: row=[3,3] The inner loop has matched every pattern symbol before the row is recorded.
Stop at first match if matched==len(pattern):break trace has four rows and scanning stops This Lab returns the first completed alignment trace, not every occurrence.
Empty pattern if pattern=="":return [[0,0]] [[0,0]] The explicit empty boundary is returned before alignment scanning.
Print Output
print(alignment_trace("aacaba","aba")) [[0, 1], [1, 1], [2, 0], [3, 3]]
print(alignment_trace("abc","")) [[0, 0]]

Use the two lengths to explain cost, then choose the method. A linear KMP guarantee and a verified rolling-hash candidate check solve different repeated-work problems.

Choose Prefix Hash or Automaton State

Choose direct comparison for short inputs, KMP for deterministic linear worst-case matching, rolling hash for many same-length windows, or an automaton/trie for multiple patterns.

Find First Pattern Occurrence

Reference
def find_pattern(text,pattern):
    if pattern=="":return 0
    for start in range(len(text)-len(pattern)+1):
        if all(text[start+offset]==character for offset,character in enumerate(pattern)):return start
    return -1
Practice

Implement find_pattern(text,pattern). Return the first start index or -1, with empty pattern at zero.

Public tests

  • Honor first and empty-pattern semantics

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Find First Pattern Occurrence

def find_pattern(text,pattern):
    if pattern=="":return 0
    for start in range(len(text)-len(pattern)+1):
        if all(text[start+offset]==character for offset,character in enumerate(pattern)):return start
    return -1

Handle Empty Patterns and Unicode

Common search APIs define the empty pattern at index zero. Python string indexes count Unicode code points, not grapheme clusters; normalization may be needed when visually equivalent text must match.

Explain It in an Interview

Say: “An alignment begins at this text index. On mismatch, this algorithm reuses this precise prior information instead of restarting blindly.” State empty behavior, overlap policy, alphabet assumptions, and complexity in text and pattern lengths.

Python Version Note

Python 3.11+

The code uses standard Python syntax and containers supported by the browser Judge. The String Matching proof does not depend on a minor Python release.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Naive alignment scanO((n-m+1)*max(1,m)) when m<=nO((n-m+1)*max(1,m)) when m<=nConstant-cost character equality; oversized patterns have no starts.
KMP search with prefix tableO(n+m)O(n+m)Plus returned match indexes.
Verified rolling-hash matchingO(n+m+C*m)O(n * max(1,m) + m)C is the number of hash candidates, including real matches; verification can dominate. Empty patterns return n+1 boundaries in the all-match interface, costing O(n+1).

Space

Naive first-match scan O(1) extra state; its alignment trace O(n); KMP prefix table O(m).

Assumptions

  • Python indexes Unicode code points, not user-perceived grapheme clusters.
  • The first-match Labs define empty pattern at 0; all-match KMP/Rabin-Karp Labs return every boundary.

Invariants Worth Saying Aloud

  1. Each possible start not safely skipped must be considered.
  2. A full match means every pattern symbol agrees, not merely a fingerprint.
  3. First-match scans stop only after all earlier starts were rejected.

When To Use Or Avoid String Matching

Use It When

  • Use simple alignment comparison for small inputs or a straightforward first-match contract.
  • Use KMP for deterministic linear matching, or verified rolling hash when window fingerprints are useful.

Choose Another Tool When

  • Several simultaneous patterns may justify a trie or automaton rather than repeating one-pattern scans.
  • Visual equivalence, case folding or grapheme boundaries require a normalization contract before matching.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Omitting the last legal alignment

For text abc and pattern bc, start 1 is legal. range(n-m) excludes it.

Prevent it: Include n-m by using range(n-m+1).

Avoid

starts=list(range(len(text)-len(pattern)))

Use instead

starts=list(range(len(text)-len(pattern)+1))

Skipping overlapping starts after a match

In aaaa, width-2 matches start at 0,1,2. Jumping by width after a match skips the middle one.

Prevent it: Advance one start for naive all-match enumeration, or use a proven prefix fallback.

Avoid

next_start=start+len(pattern)

Use instead

next_start=start+1

Treating empty pattern as absence

The first-occurrence contract places an empty pattern at zero, even in empty text.

Prevent it: Handle the documented empty-pattern result explicitly.

Avoid

answer=-1

Use instead

answer=0 if pattern=="" else -1

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.