Naive Pattern Searching for Distinct Characters Last Updated : 25 Feb, 2025 Summarize Comments Improve Suggest changes Share Like Article Like Report Question: We have discussed the Naive String matching algorithm. Consider a situation where all characters of a pattern are different. Can we modify the original Naive String Matching algorithm so that it works better for these types of patterns? If we can, then what are the changes to the original algorithm?In the original Naive String matching algorithm, we always slide the pattern by 1. When all characters of the pattern are different, we can slide the pattern by more than 1. Let us see how can we do this. When a mismatch occurs after j matches, we know that the first character of the pattern will not match the j-matched characters because all characters of the pattern are different. So we can always slide the pattern by j without missing any valid shifts. Following is the modified code that is optimized for the special patterns. N.B: This algorithm only works when the search pattern pat has all different characters. C++ /* C++ program for A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different */ #include <bits/stdc++.h> using namespace std; /* A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different */ void search(string pat, string txt) { int M = pat.size(); int N = txt.size(); int i = 0; while (i <= N - M) { int j; /* For current index i, check for pattern match */ for (j = 0; j < M; j++) if (txt[i + j] != pat[j]) break; if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1] { cout << "Pattern found at index " << i << endl; i = i + M; } else if (j == 0) i = i + 1; else i = i + j; // slide the pattern by j } } /* Driver code*/ int main() { string txt = "ABCEABCDABCEABCD"; string pat = "ABCD"; search(pat, txt); return 0; } // This code is contributed by rathbhupendra C /* C program for A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different */ #include <stdio.h> #include <string.h> /* A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different */ void search(char pat[], char txt[]) { int M = strlen(pat); int N = strlen(txt); int i = 0; while (i <= N - M) { int j; /* For current index i, check for pattern match */ for (j = 0; j < M; j++) if (txt[i + j] != pat[j]) break; if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1] { printf("Pattern found at index %d \n", i); i = i + M; } else if (j == 0) i = i + 1; else i = i + j; // slide the pattern by j } } /* Driver program to test above function */ int main() { char txt[] = "ABCEABCDABCEABCD"; char pat[] = "ABCD"; search(pat, txt); return 0; } Java /* Java program for A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different */ class GFG { /* A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different */ static void search(String pat, String txt) { int M = pat.length(); int N = txt.length(); int i = 0; while (i <= N - M) { int j; /* For current index i, check for pattern match */ for (j = 0; j < M; j++) if (txt.charAt(i + j) != pat.charAt(j)) break; if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1] { System.out.println("Pattern found at index " + i); i = i + M; } else if (j == 0) i = i + 1; else i = i + j; // slide the pattern by j } } /* Driver code*/ public static void main(String[] args) { String txt = "ABCEABCDABCEABCD"; String pat = "ABCD"; search(pat, txt); } } // This code is contributed by chandan_jnu Python # Python program for A modified Naive Pattern Searching # algorithm that is optimized for the cases when all # characters of pattern are different def search(pat, txt): M = len(pat) N = len(txt) i = 0 while i <= N-M: # For current index i, check for pattern match for j in range(M): if txt[i + j] != pat[j]: break j += 1 if j == M: # if pat[0...M-1] = txt[i, i + 1, ...i + M-1] print ("Pattern found at index " + str(i)) i = i + M elif j == 0: i = i + 1 else: i = i + j # slide the pattern by j # Driver program to test the above function txt = "ABCEABCDABCEABCD" pat = "ABCD" search(pat, txt) # This code is contributed by Bhavya Jain C# /* C# program for A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different */ using System; class GFG { /* A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different */ static void search(string pat, string txt) { int M = pat.Length; int N = txt.Length; int i = 0; while (i <= N - M) { int j; /* For current index i, check for pattern match */ for (j = 0; j < M; j++) if (txt[i + j] != pat[j]) break; if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1] { Console.WriteLine("Pattern found at index " + i); i = i + M; } else if (j == 0) i = i + 1; else i = i + j; // slide the pattern by j } } /* Driver code*/ static void Main() { string txt = "ABCEABCDABCEABCD"; string pat = "ABCD"; search(pat, txt); } } // This code is contributed by chandan_jnu JavaScript // A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different function search(pat, txt) { const M = pat.length; const N = txt.length; let i = 0; while (i <= N - M) { // For current index i, check for pattern match let j; for (j = 0; j < M; j++) { if (txt[i + j] !== pat[j]) { break; } } if (j === M) { // if pat[0...M-1] = txt[i, i + 1, ...i + M-1] console.log("Pattern found at index " + i); i = i + M; } else if (j === 0) { i = i + 1; } else { i = i + j; // slide the pattern by j } } } // Driver program to test the above function const txt = "ABCEABCDABCEABCD"; const pat = "ABCD"; search(pat, txt); PHP <?php // PHP program for A modified Naive // Pattern Searching algorithm that // is optimized for the cases when all // characters of pattern are different /* A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different */ function search($pat, $txt) { $M = strlen($pat); $N = strlen($txt); $i = 0; while ($i <= $N - $M) { $j; /* For current index i, check for pattern match */ for ($j = 0; $j < $M; $j++) if ($txt[$i + $j] != $pat[$j]) break; // if pat[0...M-1] = // txt[i, i+1, ...i+M-1] if ($j == $M) { echo("Pattern found at index $i"."\n" ); $i = $i + $M; } else if ($j == 0) $i = $i + 1; else // slide the pattern by j $i = $i + $j; } } // Driver Code $txt = "ABCEABCDABCEABCD"; $pat = "ABCD"; search($pat, $txt); // This code is contributed by nitin mittal. ?> OutputPattern found at index 4 Pattern found at index 12 Time Complexity: O(N + M), where N is the length of txt and M is the pattern length.Auxiliary Space: O(1), We are not using any extra space. Comment More infoAdvertise with us Next Article Online algorithm for checking palindrome in a stream K kartik Follow Improve Article Tags : Pattern Searching DSA Practice Tags : Pattern Searching 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 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 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", pat 14 min read Rabin-Karp Algorithm for Pattern Searching Given two strings text and pattern string, your task is to find all starting positions where the pattern appears as a substring within the text. The strings will only contain lowercase English alphabets.While reporting the results, use 1-based indexing (i.e., the first character of the text is at po 12 min read Naive Pattern Searching for Distinct Characters Question: We have discussed the Naive String matching algorithm. Consider a situation where all characters of a pattern are different. Can we modify the original Naive String Matching algorithm so that it works better for these types of patterns? If we can, then what are the changes to the original 7 min read Online algorithm for checking palindrome in a stream Given a stream of characters (characters are received one by one), write a function that prints 'Yes' if a character makes the complete string palindrome, else prints 'No'. Examples:Input: str[] = "abcba"Output: a Yes // "a" is palindrome b No // "ab" is not palindrome c No // "abc" is not palindrom 15+ min read Suffix Tree constructionGeneralized Suffix TreeIn earlier suffix tree articles, we created suffix tree for one string and then we queried that tree for substring check, searching all patterns, longest repeated substring and built suffix array (All linear time operations).There are lots of other problems where multiple strings are involved. e.g. 15+ min read Ukkonen's Suffix Tree Construction - Part 1Suffix Tree is very useful in numerous string processing and computational biology problems. Many books and e-resources talk about it theoretically and in few places, code implementation is discussed. But still, I felt something is missing and it's not easy to implement code to construct suffix tree 8 min read Ukkonen's Suffix Tree Construction - Part 2In 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 3This 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 4This 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 5This 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 6This 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 1 - Substring CheckGiven a text string and a pattern string, check if a pattern exists in text or not.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 suffix tree based algorithm.As a prerequisite, we must 15+ min read Suffix Tree Application 2 - Searching All PatternsGiven 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 SubstringGiven 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 ArrayGiven 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 SubstringGiven 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 SubstringGiven 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 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 6Inp 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 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 Like