Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Pattern Searching
  • Tutorial on Pattern Searching
  • Naive Pattern Searching
  • Rabin Karp
  • KMP Algorithm
  • Z Algorithm
  • Trie for Pattern Seaching
  • Manacher Algorithm
  • Suffix Tree
  • Ukkonen's Suffix Tree Construction
  • Boyer Moore
  • Aho-Corasick Algorithm
  • Wildcard Pattern Matching
Open In App
Next Article:
Rabin-Karp Algorithm for Pattern Searching
Next article icon

Naive algorithm for Pattern Searching

Last Updated : 20 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = “AABA”
Output: Pattern found at index 0, Pattern found at index 9, Pattern found at index 12

Pattern searching


Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. 
 

Naive Pattern Searching algorithm: 

Slide the pattern over text one by one and check for a match. If a match is found, then slide by 1 again to check for subsequent matches. 

C++
#include <iostream> #include <string> using namespace std;  void search(string& pat, string& txt) {     int M = pat.size();     int N = txt.size();      // A loop to slide pat[] one by one     for (int i = 0; i <= N - M; i++) {         int j;          // For current index i, check for pattern match         for (j = 0; j < M; j++) {             if (txt[i + j] != pat[j]) {                 break;             }         }          // If pattern matches at index i         if (j == M) {             cout << "Pattern found at index " << i << endl;         }     } }  // Driver's Code int main() {     // Example 1     string txt1 = "AABAACAADAABAABA";     string pat1 = "AABA";     cout << "Example 1: " << endl;     search(pat1, txt1);          // Example 2     string txt2 = "agd";     string pat2 = "g";     cout << "\nExample 2: " << endl;     search(pat2, txt2);      return 0; } 
C
#include <stdio.h> #include <string.h>  void search(char* pat, char* txt) {     int M = strlen(pat);     int N = strlen(txt);      // A loop to slide pat[] one by one     for (int i = 0; i <= N - M; i++) {         int j;          // For current index i, check for pattern match         for (j = 0; j < M; j++) {             if (txt[i + j] != pat[j]) {                 break;             }         }          // If pattern matches at index i         if (j == M) {             printf("Pattern found at index %d\n", i);         }     } }  int main() {     // Example 1     char txt1[] = "AABAACAADAABAABA";     char pat1[] = "AABA";     printf("Example 1:\n");     search(pat1, txt1);          // Example 2     char txt2[] = "agd";     char pat2[] = "g";     printf("\nExample 2:\n");     search(pat2, txt2);      return 0; } 
Java
public class PatternSearch {      public static void search(String pat, String txt) {         int M = pat.length();         int N = txt.length();          // A loop to slide pat[] one by one         for (int i = 0; i <= N - M; i++) {             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 pattern matches at index i             if (j == M) {                 System.out.println("Pattern found at index " + i);             }         }     }      public static void main(String[] args) {         // Example 1         String txt1 = "AABAACAADAABAABA";         String pat1 = "AABA";         System.out.println("Example 1:");         search(pat1, txt1);          // Example 2         String txt2 = "agd";         String pat2 = "g";         System.out.println("\nExample 2:");         search(pat2, txt2);     } } 
Python3
def search_pattern(pattern, text):     # Get the lengths of the pattern and the text     m = len(pattern)     n = len(text)      # A loop to slide pattern over text one by one     for i in range(n - m + 1):         # For current index i, check for pattern match         j = 0         while j < m and text[i + j] == pattern[j]:             j += 1                  # If the entire pattern matches the text starting at index i         if j == m:             print(f"Pattern found at index {i}")  # Example usage if __name__ == "__main__":     # Example 1     text1 = "AABAACAADAABAABA"     pattern1 = "AABA"     print("Example 1:")     search_pattern(pattern1, text1)          # Example 2     text2 = "agd"     pattern2 = "g"     print("\nExample 2:")     search_pattern(pattern2, text2) 
C#
using System;  class PatternSearch {     static void Search(string pat, string txt)     {         int M = pat.Length;         int N = txt.Length;          // A loop to slide pat[] one by one         for (int i = 0; i <= N - M; i++)         {             int j;              // For current index i, check for pattern match             for (j = 0; j < M; j++)             {                 if (txt[i + j] != pat[j])                 {                     break;                 }             }              // If pattern matches at index i             if (j == M)             {                 Console.WriteLine($"Pattern found at index {i}");             }         }     }      static void Main()     {         // Example 1         string txt1 = "AABAACAADAABAABA";         string pat1 = "AABA";         Console.WriteLine("Example 1:");         Search(pat1, txt1);                  // Example 2         string txt2 = "agd";         string pat2 = "g";         Console.WriteLine("\nExample 2:");         Search(pat2, txt2);     } } 
JavaScript
   function search(pat, txt) {     const M = pat.length;     const N = txt.length;      // A loop to slide pat[] one by one     for (let i = 0; i <= N - M; i++) {         let j = 0;          // For current index i, check for pattern match         while (j < M && txt[i + j] === pat[j]) {             j++;         }          // If pattern matches at index i         if (j === M) {             console.log(`Pattern found at index ${i}`);         }     } }  // Example 1 const txt1 = "AABAACAADAABAABA"; const pat1 = "AABA"; console.log("Example 1:"); search(pat1, txt1);  // Example 2 const txt2 = "agd"; const pat2 = "g"; console.log("\nExample 2:"); search(pat2, txt2); 
PHP
function search($pat, $txt) {     $M = strlen($pat);     $N = strlen($txt);      // A loop to slide pat[] one by one     for ($i = 0; $i <= $N - $M; $i++) {         $j = 0;          // For current index i, check for pattern match         while ($j < $M && $txt[$i + $j] === $pat[$j]) {             $j++;         }          // If pattern matches at index i         if ($j == $M) {             echo "Pattern found at index $i\n";         }     } }  // Example 1 $txt1 = "AABAACAADAABAABA"; $pat1 = "AABA"; echo "Example 1:\n"; search($pat1, $txt1);  // Example 2 $txt2 = "agd"; $pat2 = "g"; echo "\nExample 2:\n"; search($pat2, $txt2); 

Output
Pattern found at index 0  Pattern found at index 9  Pattern found at index 13  

Time Complexity: O(N2)
Auxiliary Space: O(1)

Complexity Analysis of Naive algorithm for Pattern Searching:

Best Case: O(n)

  • When the pattern is found at the very beginning of the text (or very early on).
  • The algorithm will perform a constant number of comparisons, typically on the order of O(n) comparisons, where n is the length of the pattern.

Worst Case: O(n2)

  • When the pattern doesn’t appear in the text at all or appears only at the very end.
  • The algorithm will perform O((n-m+1)*m) comparisons, where n is the length of the text and m is the length of the pattern.
  • In the worst case, for each position in the text, the algorithm may need to compare the entire pattern against the text.




Next Article
Rabin-Karp Algorithm for Pattern Searching
author
kartik
Improve
Article Tags :
  • DSA
  • Pattern Searching
  • Strings
  • MAQ Software
  • Oracle
  • Payu
  • Qualcomm
Practice Tags :
  • MAQ Software
  • Oracle
  • Payu
  • Qualcomm
  • Pattern Searching
  • Strings

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
    14 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences