Skip to content
DSA in JavaScript
← All patterns

String Matching

0/13 solved

What it is

Find a pattern inside a text without restarting from scratch after every mismatch, by reusing what the last comparison already told you.

Used for

Substring search, repeated patterns, longest prefix that is also a suffix.
text
a
b
a
b
c
a
b
pattern
a
b
c

Step 1 of 5

Goal: find "abc" inside "ababcab". Slide the pattern along the text and compare letter by letter.

You see

  • Find a pattern inside a text
  • Compare or transform two strings
  • Palindromes and repeated substrings

Learn it in

StringsKnuth–Morris–Pratt AlgorithmRabin Karp AlgorithmZ AlgorithmPalindrome CheckHamming DistanceLevenshtein Distance

Template

// Naive O(n * m). KMP, Rabin-Karp and Z do it in O(n + m): see their topics.const indexOf = (text, pat) => {  for (let i = 0; i + pat.length <= text.length; i++)    if (text.startsWith(pat, i)) return i;  return -1;};

Practice problems