![]() |
VOOZH | about |
Given two strings txt and pat, the task is to find if pat is a substring of txt. If yes, return the index of the first occurrence, else return -1.
Examples :
Input: txt= "geeksforgeeks", pat = "eks"
Output: 2
Explanation: String "eks" is present at index 2 and 10, so 2 is the smallest index.Input: txt= "geeksforgeeks", pat = "xyz"
Output: -1.
Explanation: There is no occurrence of "xyz" in "geeksforgeeks"
Table of Content
The basic idea is to iterate through a loop in the string txt and for every index in the string txt, check whether we can match pat starting from this index. This can be done by running a nested loop for traversing the string pat and checking for each character of pat matches with txt or not. If all character of pat matches then return the starting index of such substring.
2
Time complexity: O(m * n) where m and n are lengths of txt and pat respectively.
Auxiliary Space: O(1), as no extra space is required.
There are several Pattern Searching Algorithms like KMP Algorithm, Rabin-Karp Algorithm, Aho-Corasick Algorithm, etc. Please refer to Introduction to Pattern Searching to learn more about them.
This approach uses a built-in function to quickly check if pattern is part of text or not. This makes the process simple and efficient.
2
Note: The time complexity of in-built functions can differ across different languages.