Z algorithm (Linear time pattern searching Algorithm)
Last Updated :
16 Jul, 2024
This algorithm efficiently locates all instances of a specific pattern within a text in linear time. If the length of the text is “n” and the length of the pattern is “m,” then the total time taken is O(m + n), with a linear auxiliary space. It is worth noting that the time and auxiliary space of this algorithm is the same as the KMP algorithm, but this particular algorithm is simpler to comprehend. In this approach, we create a Z array as part of the process.
What is Z Array?
For a string str[0..n-1], Z array is of same length as string. An element Z[i] of Z array stores length of the longest substring starting from str[i] which is also a prefix of str[0..n-1]. The first entry of Z array is meaning less as complete string is always prefix of itself.
Example:
Index 0 1 2 3 4 5 6 7 8 9 10 11
Text a a b c a a b x a a a z
Z values X 1 0 0 3 1 0 0 2 2 1 0
More Examples:
str = "aaaaaa"
Z[] = {x, 5, 4, 3, 2, 1}
str = "aabaacd"
Z[] = {x, 1, 0, 2, 1, 0, 0}
str = "abababab"
Z[] = {x, 0, 6, 0, 4, 0, 2, 0}
How is Z array helpful in Searching Pattern in Linear time?
The idea is to concatenate pattern and text, and create a string “P$T” where P is pattern, $ is a special character should not be present in pattern and text, and T is text. Build the Z array for concatenated string. In Z array, if Z value at any point is equal to pattern length, then pattern is present at that point.
Example:
Pattern P = "aab", Text T = "baabaa"
The concatenated string is = "aab$baabaa"
Z array for above concatenated string is {x, 1, 0, 0, 0,
3, 1, 0, 2, 1}.
Since length of pattern is 3, the value 3 in Z array
indicates presence of pattern.
How to construct Z array?
A Simple Solution is to run two nested loops, the outer loop goes to every index and the inner loop finds length of the longest prefix that matches the substring starting at the current index. The time complexity of this solution is O(n2).
We can construct Z array in linear time.
The idea is to maintain an interval [L, R] which is the interval with max R
such that [L,R] is prefix substring (substring which is also prefix).
Steps for maintaining this interval are as follows â
1) If i > R then there is no prefix substring that starts before i and
ends after i, so we reset L and R and compute new [L,R] by comparing
str[0..] to str[i..] and get Z[i] (= R-L+1).
2) If i <= R then let K = i-L, now Z[i] >= min(Z[K], R-i+1) because
str[i..] matches with str[K..] for atleast R-i+1 characters (they are in
[L,R] interval which we know is a prefix substring).
Now two sub cases arise â
a) If Z[K] < R-i+1 then there is no prefix substring starting at
str[i] (otherwise Z[K] would be larger) so Z[i] = Z[K] and
interval [L,R] remains same.
b) If Z[K] >= R-i+1 then it is possible to extend the [L,R] interval
thus we will set L as i and start matching from str[R] onwards and
get new R then we will update interval [L,R] and calculate Z[i] (=R-L+1).
For better understanding of above step by step procedure please check this animation – http://www.utdallas.edu/~besp/demo/John2010/z-algorithm.htm
The algorithm runs in linear time because we never compare character less than R and with matching we increase R by one so there are at most T comparisons. In mismatch case, mismatch happen only once for each i (because of which R stops), thatâs another at most T comparison making overall linear complexity.
Below is the implementation of Z algorithm for pattern searching.
C++
// A C++ program that implements Z algorithm for pattern searching
#include<iostream>
using namespace std;
void getZarr(string str, int Z[]);
// prints all occurrences of pattern in text using Z algo
void search(string text, string pattern)
{
// Create concatenated string "P$T"
string concat = pattern + "$" + text;
int l = concat.length();
// Construct Z array
int Z[l];
getZarr(concat, Z);
// now looping through Z array for matching condition
for (int i = 0; i < l; ++i)
{
// if Z[i] (matched region) is equal to pattern
// length we got the pattern
if (Z[i] == pattern.length())
cout << "Pattern found at index "
<< i - pattern.length() -1 << endl;
}
}
// Fills Z array for given string str[]
void getZarr(string str, int Z[])
{
int n = str.length();
int L, R, k;
// [L,R] make a window which matches with prefix of s
L = R = 0;
for (int i = 1; i < n; ++i)
{
// if i>R nothing matches so we will calculate.
// Z[i] using naive way.
if (i > R)
{
L = R = i;
// R-L = 0 in starting, so it will start
// checking from 0'th index. For example,
// for "ababab" and i = 1, the value of R
// remains 0 and Z[i] becomes 0. For string
// "aaaaaa" and i = 1, Z[i] and R become 5
while (R<n && str[R-L] == str[R])
R++;
Z[i] = R-L;
R--;
}
else
{
// k = i-L so k corresponds to number which
// matches in [L,R] interval.
k = i-L;
// if Z[k] is less than remaining interval
// then Z[i] will be equal to Z[k].
// For example, str = "ababab", i = 3, R = 5
// and L = 2
if (Z[k] < R-i+1)
Z[i] = Z[k];
// For example str = "aaaaaa" and i = 2, R is 5,
// L is 0
else
{
// else start from R and check manually
L = i;
while (R<n && str[R-L] == str[R])
R++;
Z[i] = R-L;
R--;
}
}
}
}
// Driver program
int main()
{
string text = "GEEKS FOR GEEKS";
string pattern = "GEEK";
search(text, pattern);
return 0;
}
Java
// A Java program that implements Z algorithm for pattern
// searching
class GFG {
// prints all occurrences of pattern in text using
// Z algo
public static void search(String text, String pattern)
{
// Create concatenated string "P$T"
String concat = pattern + "$" + text;
int l = concat.length();
int Z[] = new int[l];
// Construct Z array
getZarr(concat, Z);
// now looping through Z array for matching condition
for(int i = 0; i < l; ++i){
// if Z[i] (matched region) is equal to pattern
// length we got the pattern
if(Z[i] == pattern.length()){
System.out.println("Pattern found at index "
+ (i - pattern.length() - 1));
}
}
}
// Fills Z array for given string str[]
private static void getZarr(String str, int[] Z) {
int n = str.length();
// [L,R] make a window which matches with
// prefix of s
int L = 0, R = 0;
for(int i = 1; i < n; ++i) {
// if i>R nothing matches so we will calculate.
// Z[i] using naive way.
if(i > R){
L = R = i;
// R-L = 0 in starting, so it will start
// checking from 0'th index. For example,
// for "ababab" and i = 1, the value of R
// remains 0 and Z[i] becomes 0. For string
// "aaaaaa" and i = 1, Z[i] and R become 5
while(R < n && str.charAt(R - L) == str.charAt(R))
R++;
Z[i] = R - L;
R--;
}
else{
// k = i-L so k corresponds to number which
// matches in [L,R] interval.
int k = i - L;
// if Z[k] is less than remaining interval
// then Z[i] will be equal to Z[k].
// For example, str = "ababab", i = 3, R = 5
// and L = 2
if(Z[k] < R - i + 1)
Z[i] = Z[k];
// For example str = "aaaaaa" and i = 2, R is 5,
// L is 0
else{
// else start from R and check manually
L = i;
while(R < n && str.charAt(R - L) == str.charAt(R))
R++;
Z[i] = R - L;
R--;
}
}
}
}
// Driver program
public static void main(String[] args)
{
String text = "GEEKS FOR GEEKS";
String pattern = "GEEK";
search(text, pattern);
}
}
// This code is contributed by PavanKoli.
Python
# Python3 program that implements Z algorithm
# for pattern searching
# Fills Z array for given string str[]
def getZarr(string, z):
n = len(string)
# [L,R] make a window which matches
# with prefix of s
l, r, k = 0, 0, 0
for i in range(1, n):
# if i>R nothing matches so we will calculate.
# Z[i] using naive way.
if i > r:
l, r = i, i
# R-L = 0 in starting, so it will start
# checking from 0'th index. For example,
# for "ababab" and i = 1, the value of R
# remains 0 and Z[i] becomes 0. For string
# "aaaaaa" and i = 1, Z[i] and R become 5
while r < n and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
else:
# k = i-L so k corresponds to number which
# matches in [L,R] interval.
k = i - l
# if Z[k] is less than remaining interval
# then Z[i] will be equal to Z[k].
# For example, str = "ababab", i = 3, R = 5
# and L = 2
if z[k] < r - i + 1:
z[i] = z[k]
# For example str = "aaaaaa" and i = 2,
# R is 5, L is 0
else:
# else start from R and check manually
l = i
while r < n and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
# prints all occurrences of pattern
# in text using Z algo
def search(text, pattern):
# Create concatenated string "P$T"
concat = pattern + "$" + text
l = len(concat)
# Construct Z array
z = [0] * l
getZarr(concat, z)
# now looping through Z array for matching condition
for i in range(l):
# if Z[i] (matched region) is equal to pattern
# length we got the pattern
if z[i] == len(pattern):
print("Pattern found at index",
i - len(pattern) - 1)
# Driver Code
if __name__ == "__main__":
text = "GEEKS FOR GEEKS"
pattern = "GEEK"
search(text, pattern)
# This code is contributed by
# sanjeev2552
C#
// A C# program that implements Z
// algorithm for pattern searching
using System;
class GFG
{
// prints all occurrences of
// pattern in text using Z algo
public static void search(string text,
string pattern)
{
// Create concatenated string "P$T"
string concat = pattern + "$" + text;
int l = concat.Length;
int[] Z = new int[l];
// Construct Z array
getZarr(concat, Z);
// now looping through Z array
// for matching condition
for (int i = 0; i < l; ++i)
{
// if Z[i] (matched region) is equal
// to pattern length we got the pattern
if (Z[i] == pattern.Length)
{
Console.WriteLine("Pattern found at index " +
(i - pattern.Length - 1));
}
}
}
// Fills Z array for given string str[]
private static void getZarr(string str,
int[] Z)
{
int n = str.Length;
// [L,R] make a window which
// matches with prefix of s
int L = 0, R = 0;
for (int i = 1; i < n; ++i)
{
// if i>R nothing matches so we will
// calculate. Z[i] using naive way.
if (i > R)
{
L = R = i;
// R-L = 0 in starting, so it will start
// checking from 0'th index. For example,
// for "ababab" and i = 1, the value of R
// remains 0 and Z[i] becomes 0. For string
// "aaaaaa" and i = 1, Z[i] and R become 5
while (R < n && str[R - L] == str[R])
{
R++;
}
Z[i] = R - L;
R--;
}
else
{
// k = i-L so k corresponds to number
// which matches in [L,R] interval.
int k = i - L;
// if Z[k] is less than remaining interval
// then Z[i] will be equal to Z[k].
// For example, str = "ababab", i = 3,
// R = 5 and L = 2
if (Z[k] < R - i + 1)
{
Z[i] = Z[k];
}
// For example str = "aaaaaa" and
// i = 2, R is 5, L is 0
else
{
// else start from R and
// check manually
L = i;
while (R < n && str[R - L] == str[R])
{
R++;
}
Z[i] = R - L;
R--;
}
}
}
}
// Driver Code
public static void Main(string[] args)
{
string text = "GEEKS FOR GEEKS";
string pattern = "GEEK";
search(text, pattern);
}
}
// This code is contributed by Shrikant13
Javascript
<script>
// A JavaScript program that implements Z algorithm for pattern
// searching
// prints all occurrences of pattern in text using
// Z algo
function search(text,pattern)
{
// Create concatenated string "P$T"
let concat = pattern + "$" + text;
let l = concat.length;
let Z = new Array(l);
// Construct Z array
getZarr(concat, Z);
// now looping through Z array for matching condition
for(let i = 0; i < l; ++i){
// if Z[i] (matched region) is equal to pattern
// length we got the pattern
if(Z[i] == pattern.length){
document.write("Pattern found at index "
+ (i - pattern.length - 1)+"<br>");
}
}
}
// Fills Z array for given string str[]
function getZarr(str,Z)
{
let n = str.length;
// [L,R] make a window which matches with
// prefix of s
let L = 0, R = 0;
for(let i = 1; i < n; ++i) {
// if i>R nothing matches so we will calculate.
// Z[i] using naive way.
if(i > R){
L = R = i;
// R-L = 0 in starting, so it will start
// checking from 0'th index. For example,
// for "ababab" and i = 1, the value of R
// remains 0 and Z[i] becomes 0. For string
// "aaaaaa" and i = 1, Z[i] and R become 5
while(R < n && str[R - L] == str[R])
R++;
Z[i] = R - L;
R--;
}
else{
// k = i-L so k corresponds to number which
// matches in [L,R] interval.
let k = i - L;
// if Z[k] is less than remaining interval
// then Z[i] will be equal to Z[k].
// For example, str = "ababab", i = 3, R = 5
// and L = 2
if(Z[k] < R - i + 1)
Z[i] = Z[k];
// For example str = "aaaaaa" and i = 2, R is 5,
// L is 0
else{
// else start from R and check manually
L = i;
while(R < n && str[R - L] == str[R])
R++;
Z[i] = R - L;
R--;
}
}
}
}
// Driver program
let text = "GEEKS FOR GEEKS";
let pattern = "GEEK";
search(text, pattern);
// This code is contributed by rag2127
</script>
Output:
Pattern found at index 0
Pattern found at index 10
Time Complexity: O(m+n), where m is length of pattern and n is length of text.
Auxiliary Space: O(n)
Similar Reads
What is Pattern Searching ?
Pattern searching in Data Structures and Algorithms (DSA) is a fundamental concept that involves searching for a specific pattern or sequence of elements within a given data structure. This technique is commonly used in string matching algorithms to find occurrences of a particular pattern within a
5 min read
Introduction to Pattern Searching - Data Structure and Algorithm Tutorial
Pattern searching is an algorithm that involves searching for patterns such as strings, words, images, etc. We use certain algorithms to do the search process. The complexity of pattern searching varies from algorithm to algorithm. They are very useful when performing a search in a database. The Pat
15+ min read
Naive algorithm for Pattern Searching
Given text string with length n and a pattern with length m, the task is to prints all occurrences of pattern in text. Note: You may assume that n > m. Examples:Â Input: Â text = "THIS IS A TEST TEXT", pattern = "TEST"Output: Pattern found at index 10 Input: Â text = Â "AABAACAADAABAABA", pattern =
6 min read
Rabin-Karp Algorithm for Pattern Searching
Given a text T[0. . .n-1] and a pattern P[0. . .m-1], write a function search(char P[], char T[]) that prints all occurrences of P[] present in T[] using Rabin Karp algorithm. You may assume that n > m. Examples: Input: T[] = "THIS IS A TEST TEXT", P[] = "TEST"Output: Pattern found at index 10 In
15 min read
KMP Algorithm for Pattern Searching
Given two strings txt and pat, the task is to return all indices of occurrences of pat within txt. Examples: Input: txt = "abcab", pat = "ab"Output: [0, 3]Explanation: The string "ab" occurs twice in txt, first occurrence starts from index 0 and second from index 3. Input: txt= "aabaacaadaabaaba", p
12 min read
Z algorithm (Linear time pattern searching Algorithm)
This algorithm efficiently locates all instances of a specific pattern within a text in linear time. If the length of the text is "n" and the length of the pattern is "m," then the total time taken is O(m + n), with a linear auxiliary space. It is worth noting that the time and auxiliary space of th
13 min read
Finite Automata algorithm for Pattern Searching
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m.Examples: Input: txt[] = "THIS IS A TEST TEXT" pat[] = "TEST" Output: Pattern found at index 10 Input: txt[] = "AABAACAADAAB
13 min read
Boyer Moore Algorithm for Pattern Searching
Pattern searching is an important problem in computer science. When we do search for a string in a notepad/word file, browser, or database, pattern searching algorithms are used to show the search results. A typical problem statement would be-Â " Given a text txt[0..n-1] and a pattern pat[0..m-1] wh
15+ min read
Aho-Corasick Algorithm for Pattern Searching
Given an input text and an array of k words, arr[], find all occurrences of all words in the input text. Let n be the length of text and m be the total number of characters in all words, i.e. m = length(arr[0]) + length(arr[1]) + ... + length(arr[k-1]). Here k is total numbers of input words. Exampl
15+ min read
ÂÂkasaiâs Algorithm for Construction of LCP array from Suffix Array
Background Suffix Array : A suffix array is a sorted array of all suffixes of a given string. Let the given string be "banana". 0 banana 5 a1 anana Sort the Suffixes 3 ana2 nana ----------------> 1 anana 3 ana alphabetically 0 banana 4 na 4 na 5 a 2 nanaThe suffix array for "banana" :suffix[] = {
15+ min read
Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 4
In Manacher's Algorithm Part 1 and Part 2, we gone through some of the basics, understood LPS length array and how to calculate it efficiently based on four cases. In Part 3, we implemented the same. Here we will review the four cases again and try to see it differently and implement the same. All f
12 min read
Suffix Tree construction
Ukkonen's Suffix Tree Construction - Part 2
In Ukkonenâs Suffix Tree Construction â Part 1, we have seen high level Ukkonenâs Algorithm. This 2nd part is continuation of Part 1. Please go through Part 1, before looking at current article. In Suffix Tree Construction of string S of length m, there are m phases and for a phase j (1 <= j <
11 min read
Ukkonen's Suffix Tree Construction - Part 3
This article is continuation of following two articles: Ukkonenâs Suffix Tree Construction â Part 1 Ukkonenâs Suffix Tree Construction â Part 2 Please go through Part 1 and Part 2, before looking at current article, where we have seen few basics on suffix tree, high level ukkonenâs algorithm, suffix
15 min read
Ukkonen's Suffix Tree Construction - Part 4
This article is continuation of following three articles: Ukkonenâs Suffix Tree Construction â Part 1 Ukkonenâs Suffix Tree Construction â Part 2 Ukkonenâs Suffix Tree Construction â Part 3 Please go through Part 1, Part 2 and Part 3, before looking at current article, where we have seen few basics
11 min read
Ukkonen's Suffix Tree Construction - Part 5
This article is continuation of following four articles: Ukkonenâs Suffix Tree Construction â Part 1 Ukkonenâs Suffix Tree Construction â Part 2 Ukkonenâs Suffix Tree Construction â Part 3 Ukkonenâs Suffix Tree Construction â Part 4 Please go through Part 1, Part 2, Part 3 and Part 4, before looking
13 min read
Ukkonen's Suffix Tree Construction - Part 6
This article is continuation of following five articles: Ukkonenâs Suffix Tree Construction â Part 1 Ukkonenâs Suffix Tree Construction â Part 2 Ukkonenâs Suffix Tree Construction â Part 3 Ukkonenâs Suffix Tree Construction â Part 4 Ukkonenâs Suffix Tree Construction â Part 5Please go through Part 1
15+ min read
Suffix Tree Application
Suffix Tree Application 2 - Searching All Patterns
Given a text string and a pattern string, find all occurrences of the pattern in string. Few pattern searching algorithms (KMP, Rabin-Karp, Naive Algorithm, Finite Automata) are already discussed, which can be used for this check. Here we will discuss the suffix tree based algorithm. In the 1st Suff
15+ min read
Suffix Tree Application 3 - Longest Repeated Substring
Given a text string, find Longest Repeated Substring in the text. If there are more than one Longest Repeated Substrings, get any one of them. Longest Repeated Substring in GEEKSFORGEEKS is: GEEKS Longest Repeated Substring in AAAAAAAAAA is: AAAAAAAAA Longest Repeated Substring in ABCDEFG is: No rep
15+ min read
Suffix Tree Application 4 - Build Linear Time Suffix Array
Given a string, build it's Suffix Array We have already discussed following two ways of building suffix array: Naive O(n2Logn) algorithmEnhanced O(nLogn) algorithm Please go through these to have the basic understanding. Here we will see how to build suffix array in linear time using suffix tree.As
15+ min read
Suffix Tree Application 5 - Longest Common Substring
Given two strings X and Y, find the Longest Common Substring of X and Y.Naive [O(N*M2)] and Dynamic Programming [O(N*M)] approaches are already discussed here. In this article, we will discuss a linear time approach to find LCS using suffix tree (The 5th Suffix Tree Application). Here we will build
15+ min read
Suffix Tree Application 6 - Longest Palindromic Substring
Given a string, find the longest substring which is palindrome.We have already discussed NaÃŊve [O(n3)], quadratic [O(n2)] and linear [O(n)] approaches in Set 1, Set 2 and Manacherâs Algorithm. In this article, we will discuss another linear time approach based on suffix tree. If given string is S, t
15+ min read
More practice problems on pattern searching algorithms
Pattern Searching using C++ library
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function that prints all occurrences of pat[] in txt[]. You may assume that n > m.Examples: Input : txt[] = "geeks for geeks" pat[] = "geeks" Output : Pattern found at index 0 Pattern found at index 10 Input : txt[] = "aaaa" pat[] = "aa"
3 min read
Anagram Substring Search (Or Search for all permutations)
Given a text txt and a pattern pat of size n and m respectively, the task is to find all occurrences of pat and its permutations (or anagrams) in txt. You may assume n > m. Examples: Input: txt = "BACDGABCDA", pat = "ABCD"Output: [0, 5, 6]Explanation: "BACD" is at 0, "ABCD" at 5 and "BCDA" at 6In
7 min read
Pattern Searching using a Trie of all Suffixes
Problem Statement: Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m.As discussed in the previous post, we discussed that there are two ways efficiently solve the above probl
13 min read
Wildcard Pattern Matching in Linear Time and Constant Space
Given two strings 'str' and a wildcard pattern 'pattern' of length n and m respectively, the task is to return '1' if the wildcard pattern is matched with str else return '0'. All characters of the string str and pattern always belong to the alphanumeric characters. â?â â matches any single characte
8 min read
Longest prefix which is also suffix
Given a string s, the task is to find the length of the longest proper prefix which is also a suffix. A proper prefix is a prefix that doesnât include whole string. For example, prefixes of "abc" are "", "a", "ab" and "abc" but proper prefixes are "", "a" and "ab" only. Examples: Input: s = "aabcdaa
11 min read
Count of number of given string in 2D character array
Given a 2-dimensional character array and a string, we need to find the given string in a 2-dimensional character array, such that individual characters can be present left to right, right to left, top to down or down to top. Examples: Input : a ={ {D,D,D,G,D,D}, {B,B,D,E,B,S}, {B,S,K,E,B,K}, {D,D,D
9 min read
Find all the patterns of "1(0+)1" in a given string (General Approach)
A string contains patterns of the form 1(0+)1 where (0+) represents any non-empty consecutive sequence of 0's. Count all such patterns. The patterns are allowed to overlap. Note : It contains digits and lowercase characters only. The string is not necessarily a binary. 100201 is not a valid pattern.
5 min read
Maximum length prefix of one string that occurs as subsequence in another
Given two strings s and t. The task is to find maximum length of some prefix of the string S which occur in string t as subsequence. Examples : Input : s = "digger" t = "biggerdiagram" Output : 3 digger biggerdiagram Prefix "dig" of s is longest subsequence in t. Input : s = "geeksforgeeks" t = "agb
5 min read
Wildcard Pattern Matching
Given a text txt and a wildcard pattern pat, implement a wildcard pattern matching algorithm that finds if the wildcard pattern is matched with the text. The matching should cover the entire text. The wildcard pattern can include the characters '?' and '*' which denote: '?' - matches any single char
15+ min read
Word Search in a 2D Grid of characters
Given a 2D grid m*n of characters and a word, the task is to find all occurrences of the given word in the grid. A word can be matched in all 8 directions at any point. Word is said to be found in a direction if all characters match in this direction (not in zig-zag form).The 8 directions are, Horiz
15+ min read
String matching where one string contains wildcard characters
Given two strings where first string may contain wild card characters and second string is a normal string. Write a function that returns true if the two strings match. The following are allowed wild card characters in first string. * --> Matches with 0 or more instances of any character or set o
9 min read