The Wayback Machine - https://web.archive.org/web/20240922061903/https://www.geeksforgeeks.org/optimized-naive-algorithm-for-pattern-searching/
Open In App

Optimized Algorithm for Pattern Searching

Last Updated : 14 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Question: We have discussed the Naive String matching algorithm here. 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?

Solution: 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


Python3




# 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


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.
?>


Javascript




<script>
 
// Javascript 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)
{
    let M = pat.length;
    let N = txt.length;
    let i = 0;
 
    while (i <= N - M)
    {
        let 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) 
        {
            document.write("Pattern found at index " +
                           i + "<br/>");
            i = i + M;
        }
        else if (j == 0)
            i = i + 1;
        else
         
            // Slide the pattern by j
            i = i + j;
    }
}
     
// Driver code
let txt = "ABCEABCDABCEABCD";
let pat = "ABCD";
 
search(pat, txt);
 
// This code is contributed by target_2
 
</script>


Output

Pattern 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 pat length.
Auxiliary Space: O(1), We are not using any extra space.

 



Previous Article
Next Article

Similar Reads

Real time optimized KMP Algorithm for Pattern Searching
In the article, we have already discussed the KMP algorithm for pattern searching. In this article, a real-time optimized KMP algorithm is discussed. From the previous article, it is known that KMP(a.k.a. Knuth-Morris-Pratt) algorithm preprocesses the pattern P and constructs a failure function F(also called as lps[]) to store the length of the lon
7 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 this algorithm is the same as the KMP algorithm, but
13 min read
Rabin-Karp algorithm for Pattern Searching in Matrix
Given matrices txt[][] of dimensions m1 x m2 and pattern pat[][] of dimensions n1 x n2, the task is to check whether a pattern exists in the matrix or not, and if yes then print the top most indices of the pat[][] in txt[][]. It is assumed that m1, m2 ? n1, n2 Examples: Input: txt[][] = {{G, H, I, P} {J, K, L, Q} {R, G, H, I} {S, J, K, L} } pat[][]
15+ 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 &gt; m. Examples: Input: T[] = "THIS IS A TEST TEXT", P[] = "TEST"Output: Pattern found at index 10 Input: T[] = "AABAACAADAABAABA", P[] = "AABA"Output:
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. Example: Input: text = "ahishers" arr[] = {"he", "she",
15+ 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] where n is the length of the text and m is the lengt
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 &gt; m. Examples:  Input:  text = "THIS IS A TEST TEXT", pattern = "TEST"Output: Pattern found at index 10 Input:  text =  "AABAACAADAABAABA", pattern = "AABA"Output: Pattern found at index 0, Pattern fo
6 min read
KMP Algorithm for Pattern Searching
Given two strings txt and pat of size N and M, where N &gt; M. String txt and pat represent the text and pattern respectively. The task is to print all indexes of occurrences of pattern string in the text string. Use one-based indexing while returning the indices. Examples: Input:  txt = "THIS IS A TEST TEXT", pat = "TEST"Output: Pattern found at i
15+ 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 &gt; m.Examples: Input: txt[] = "THIS IS A TEST TEXT" pat[] = "TEST" Output: Pattern found at index 10 Input: txt[] = "AABAACAADAABAABA" pat[] = "AABA" Output: Pattern found at inde
13 min read
Union-Find Algorithm | (Union By Rank and Find by Optimized Path Compression)
Check whether a given graph contains a cycle or not. Example: Input: Output: Graph contains Cycle. Input: Output: Graph does not contain Cycle. Prerequisites: Disjoint Set (Or Union-Find), Union By Rank and Path CompressionWe have already discussed union-find to detect cycle. Here we discuss find by path compression, where it is slightly modified t
13 min read
Barrett Reduction Algorithm (Optimized Variant)
The Barrett Reduction Algorithm computes the remainder of a big integer x divided by another large integer mod. The procedure precomputes mu, the inverse of mod with regard to the next power of 2. All mod calculations utilize this value. Approach: The Barrett Reduction Algorithm approximates x divided by mod using the precomputed value mu. The proc
8 min read
Dial's Algorithm (Optimized Dijkstra for small range weights)
Dijkstra’s shortest path algorithm runs in O(Elog V) time when implemented with adjacency list representation (See C implementation and STL based C++ implementations for details). Input : Source = 0, Maximum Weight W = 14Output : Vertex Distance from Source 0 0 1 4 2 12 3 19 4 21 5 11 6 9 7 8 8 14 Consider the below Graph: We have learned about how
15+ 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 &gt; 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" Output : Pattern found at index 0 Pattern found a
3 min read
Pattern Searching | Set 6 (Efficient Construction of Finite Automata)
In the previous post, we discussed the Finite Automata-based pattern searching algorithm. The FA (Finite Automata) construction method discussed in the previous post takes O((m^3)*NO_OF_CHARS) time. FA can be constructed in O(m*NO_OF_CHARS) time. In this post, we will discuss the O(m*NO_OF_CHARS) algorithm for FA construction. The idea is similar t
9 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 &gt; m.As discussed in the previous post, we discussed that there are two ways efficiently solve the above problem.1) Preprocess Pattern: KMP Algorithm, Rabin Kar
13 min read
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 text or a larger string. By using various algorith
5 min read
Pattern Searching using Suffix Tree
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 &gt; m. Preprocess Pattern or Preprocess Text? We have discussed the following algorithms in the previous posts: KMP Algorithm Rabin Karp Algorithm Finite Automata based Algorithm B
4 min read
Introduction to Pattern Searching
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 Pattern Searching algorithm is useful for finding pat
15+ min read
Pattern Searching
Pattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Pattern searching algorithms play important role in tasks such as text processing, data mining, and information retrieval. What is Pattern Searching?Pattern sea
4 min read
Boyer-Moore Majority Voting Algorithm for Searching elements having more than K Occurrences
The Boyer-Moore Majority Voting Algorithm is a well-known and efficient algorithm used to find the majority element in an array, i.e., an element that appears more than n/2 times. This algorithm, initially designed by Robert S. Boyer and J Strother Moore in 1981, is widely used in various applications, including data analysis and stream processing.
9 min read
Fastest Searching Algorithm | GFact
Pattern searching is a critical operation in the field of computer science, Its applications range from text processing and DNA sequencing to image recognition and data mining. As data sizes grow exponentially, the demand for faster pattern-searching algorithms has only grown. Which is the Fastest Searching Algorithm?One of the best algorithms is t
2 min read
Longest Common Substring (Space optimized DP solution)
Given two strings 'X' and 'Y', find the length of longest common substring. Expected space complexity is linear.Examples : Input : X = "GeeksforGeeks", Y = "GeeksQuiz" Output : 5 The longest common substring is "Geeks" and is of length 5. Input : X = "abcdxyz", Y = "xyzabcd" Output : 4 The longest common substring is "abcd" and is of length 4. We h
9 min read
Number of n digit stepping numbers | Space optimized solution
Given n, find the count of n digit Stepping numbers. A number is called a stepping number if all adjacent digits have an absolute difference of 1. 321 is a Stepping Number while 421 is not.Examples: Input : 2 Output : 17 The numbers are 10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65, 67, 76, 78, 87, 89, 98. Input : 1 Output : 10 The numbers are 0, 1, 2
9 min read
Counts paths from a point to reach Origin : Memory Optimized
Given two integers N and M, which denotes the position of in the coordinate system, the task is to count path from this point to reach origin by taking steps either left or down.Examples: Input: 3 6 Output: Number of Paths 84Input: 3 3 Output: Number of Paths 20 We have already discussed this problem in this article - Counts paths from a point to r
6 min read
Print Longest Bitonic subsequence (Space Optimized Approach)
Given an array arr[] of size N, the task is to print the longest bitonic subsequence of the given array.Note: If more than one solution exit then prints anyone solution. Examples: Input: arr[] = {1, 11, 2, 10, 4, 5, 2, 1} Output: 1 11 10 5 2 1 Explanation: All possible longest bitonic subsequences from the above array are {1, 2, 10, 4, 2, 1}, {1, 1
11 min read
Optimized Longest Path is NP Complete
Optimized Longest Path Problem: The optimized longest path problem states that given a graph G, of a set of vertices V and edges E, the task is to prove that there is a path of length at least K between a set of nodes Vs and Ve. Problem Statement: Given a graph G(V, E, K) and a set of nodes Vs and Ve with the sequence of nodes, of length ≥ K. Expla
4 min read
Design and Implement Special Stack Data Structure | Added Space Optimized Version
Question: Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must be O(1). To implement SpecialStack, you should only use standard Stack data structure
15+ min read
Word Wrap problem ( Space optimized solution )
Given a sequence of words, and a limit on the number of characters that can be put in one line (line width). Put line breaks in the given sequence such that the lines are printed neatly. Assume that the length of each word is smaller than the line width. When line breaks are inserted there is a possibility that extra spaces are present in each line
15+ min read
Printing Matrix Chain Multiplication (A Space Optimized Solution)
Prerequisite : Dynamic Programming | Set 8 (Matrix Chain Multiplication)Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications. We have many options to multiply a chain of matrices be
12 min read
A Space Optimized DP solution for 0-1 Knapsack Problem
Given the weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the max
15+ min read
Article Tags :
Practice Tags :