CodeMosa

Master LeetCode Patterns

AdvancedAdvanced Patterns

KMP Algorithm

Linear-time substring search via prefix function (lps) to avoid re-scanning.

Time: O(n+m)
Space: O(m)

What is KMP Algorithm?

#
Definition: Linear-time substring search using the prefix function (lps) to avoid re-scanning characters.

Core Idea

#

Precompute the longest proper prefix that is also a suffix (lps) for the pattern; while scanning the text, fall back using lps instead of restarting.

When to Use

#

Use when you need deterministic O(n+m) substring search without hashing or when building editors/search tools.

How KMP Algorithm works

#

Build lps (prefix function), then scan text and reuse lps to avoid backtracking.

  • Find pattern in text
  • All occurrences
  • Avoid backtracking

KMP Algorithm vs alternatives

#

Use this pattern when use when you need deterministic o(n+m) substring search without hashing or when building editors/search tools.

General Recognition Cues

#
General indicators that this pattern might be applicable
  • Find pattern in text
  • All occurrences
  • Avoid backtracking
#
Curated practice sets for this pattern

Code Templates

#
Build lps (prefix function), then scan text and reuse lps to avoid backtracking.
def kmp_search(s, p):
    # build lps
    lps=[0]*len(p); k=0
    for i in range(1,len(p)):
        while k>0 and p[k]!=p[i]: k=lps[k-1]
        if p[k]==p[i]: k+=1; lps[i]=k
    # search
    j=0; res=[]
    for i,ch in enumerate(s):
        while j>0 and p[j]!=ch: j=lps[j-1]
        if p[j]==ch: j+=1
        if j==len(p): res.append(i-j+1); j=lps[j-1]
    return res

Pattern Variants & Approaches

#
Different methodologies and implementations for this pattern
1

Prefix Function (lps)

#

Compute lps in O(m) and reuse during search.

When to Use This Variant
  • Overlap of prefix/suffix
Use Case
Search/replace, occurrences
Advantages
  • O(n+m)
  • Deterministic
Implementation
def kmp_search(s, p):
    # build lps
    lps=[0]*len(p); k=0
    for i in range(1,len(p)):
        while k>0 and p[k]!=p[i]: k=lps[k-1]
        if p[k]==p[i]: k+=1; lps[i]=k
    # search
    j=0; res=[]
    for i,ch in enumerate(s):
        while j>0 and p[j]!=ch: j=lps[j-1]
        if p[j]==ch: j+=1
        if j==len(p): res.append(i-j+1); j=lps[j-1]
    return res

Common Pitfalls

#
Watch out for these common mistakes
  • Off-by-one in lps
  • Resetting j using lps[j-1]
  • Empty pattern edge case
#

Example Problems

#
Classic LeetCode problems using this pattern

Complexity Analysis

#
Time Complexity
O(n+m)

Build lps in O(m), scan text once.

Space Complexity
O(m)

lps array of size m.

Ready to test your knowledge?

Test your pattern recognition with interactive questions