Z Algorithm
Pattern matching in O(n). Z[i] = length of longest substring at i matching prefix.
Visualization
Interactive visualization for Z Algorithm
Z Algorithm (Pattern Matching)
Text:
• Time: O(n + m) linear time
• Z[i] = length of longest substring starting at i matching prefix
• Efficient for multiple pattern searches
Interactive visualization with step-by-step execution
Implementation
1function zAlgorithm(text: string, pattern: string): number[] {
2 const s = pattern + '$' + text;
3 const Z = new Array(s.length).fill(0);
4 let L = 0, R = 0;
5
6 for (let i = 1; i < s.length; i++) {
7 if (i > R) {
8 L = R = i;
9 while (R < s.length && s[R] === s[R - L]) R++;
10 Z[i] = R - L; R--;
11 } else {
12 if (Z[i - L] < R - i + 1) Z[i] = Z[i - L];
13 else {
14 L = i;
15 while (R < s.length && s[R] === s[R - L]) R++;
16 Z[i] = R - L; R--;
17 }
18 }
19 }
20
21 return Z.slice(pattern.length + 1).map((v, i) => v === pattern.length ? i : -1).filter(i => i >= 0);
22}Deep Dive
Theoretical Foundation
Z-array for pattern matching. Uses previously computed values to skip comparisons.
Complexity
Time
O(n+m)
O(n+m)
O(n+m)
Space
O(n+m)
Applications
Industry Use
Text editors (find and replace functionality)
Bioinformatics (DNA/RNA sequence matching)
Web search engines (keyword matching)
Plagiarism detection systems
Data mining and text analysis
Compiler construction (lexical analysis)
Network intrusion detection
Use Cases
Related Algorithms
Knuth-Morris-Pratt (KMP) Algorithm
An efficient string pattern matching algorithm that searches for occurrences of a 'word' within a 'text' by employing the observation that when a mismatch occurs, the word itself embodies sufficient information to determine where the next match could begin. Developed by Donald Knuth, Vaughan Pratt, and James H. Morris in 1977, it's one of the most important string algorithms with O(n+m) time complexity.
Rabin-Karp Algorithm
A string-searching algorithm that uses hashing to find pattern(s) in a text. Developed by Michael O. Rabin and Richard M. Karp in 1987, it's particularly useful for multiple pattern search and plagiarism detection. Uses rolling hash for efficiency.
Boyer-Moore Algorithm
One of the most efficient string searching algorithms in practice, using two heuristics: bad character rule and good suffix rule. Developed by Robert S. Boyer and J Strother Moore in 1977, it's the standard benchmark for practical string search, often outperforming other algorithms by skipping sections of text.
Aho-Corasick Algorithm
A string-searching algorithm for locating elements of a finite set of strings (dictionary) within an input text. Invented by Alfred V. Aho and Margaret J. Corasick in 1975, it's a kind of dictionary-matching algorithm that simultaneously searches for all patterns in linear time, making it extremely efficient for multiple pattern matching.