Given two strings txt and pat, return the 0-based index of the first occurrence of the substring pat in txt. If pat is not found, return -1.
Examples:
Input: txt = "GeeksForGeeks", pat = "Fr"
Output: -1
Explanation: "Fr" is not present in the string "GeeksForGeeks" as substring.Input: txt = "GeeksForGeeks", pat = "For"
Output: 5
Explanation: "For" is present as substring in "GeeksForGeeks" from index 5 (0 based indexing).Input: txt = "GeeksForGeeks", pat = "gr"
Output: -1
Explanation: "gr" is not present in the string "GeeksForGeeks" as substring.
Table of Content
Nested loops - O(n * m) Time and O(1) Space
The basic idea is to traverse the string txt and check whether pat matches starting from each index. For every index, use a nested loop to compare the characters of pat with the corresponding characters of txt.
- If all characters of pat match, return the starting index.
- If a mismatch occurs, move to the next index of txt.
- Return -1 if pat is not found in txt.
#include
using namespace std;
// Function to find if pat is a substring of txt
int firstOccurence(string &txt, string &pat)
{
int n = txt.length();
int m = pat.length();
// Iterate through txt
for (int i = 0; i <= n - m; i++)
{
// Check for substring match
int j;
for (j = 0; j < m; j++)
{
// Mismatch found
if (txt[i + j] != pat[j])
{
break;
}
}
// If we completed the inner loop, we found a match
if (j == m)
{
// Return starting index
return i;
}
}
// No match found
return -1;
}
int main()
{
string txt = "GeeksForGeeks";
string pat = "For";
cout << firstOccurence(txt, pat);
return 0;
}
#include
#include
// Function to find if pat is a substring of txt
int firstOccurence(char *txt, char *pat)
{
int n = strlen(txt);
int m = strlen(pat);
// Iterate through txt
for (int i = 0; i <= n - m; i++)
{
// Check for substring match
int j;
for (j = 0; j < m; j++)
{
// Mismatch found
if (txt[i + j] != pat[j])
{
break;
}
}
// If we completed the inner loop, we found a match
if (j == m)
{
// Return starting index
return i;
}
}
// No match found
return -1;
}
int main()
{
char txt[] = "geeksforgeeks";
char pat[] = "eks";
printf("%d", firstOccurence(txt, pat));
return 0;
}
class GFG {
// Function to find if pat is a substring of txt
static int firstOccurence(String txt, String pat)
{
int n = txt.length();
int m = pat.length();
// Iterate through txt
for (int i = 0; i <= n - m; i++) {
// Check for substring match
int j;
for (j = 0; j < m; j++) {
// Mismatch found
if (txt.charAt(i + j) != pat.charAt(j)) {
break;
}
}
// If we completed the inner loop, we found a
// match
if (j == m) {
// Return starting index
return i;
}
}
// No match found
return -1;
}
public static void main(String[] args)
{
String txt = "geeksforgeeks";
String pat = "eks";
System.out.println(firstOccurence(txt, pat));
}
}
def firstOccurence(txt, pat):
n = len(txt)
m = len(pat)
# Iterate through txt
for i in range(n - m + 1):
# Check for substring match
j = 0
while j < m and txt[i + j] == pat[j]:
j += 1
# If we completed the inner loop, we found a match
if j == m:
return i
# No match found
return -1
if __name__ == "__main__":
txt = "geeksforgeeks"
pat = "eks"
print(firstOccurence(txt, pat))
using System;
class GFG {
// Function to find if pat is a substring of txt
static int firstOccurence(string txt, string pat)
{
int n = txt.Length;
int m = pat.Length;
// Iterate through txt
for (int i = 0; i <= n - m; i++) {
// Check for substring match
int j;
for (j = 0; j < m; j++) {
// Mismatch found
if (txt[i + j] != pat[j]) {
break;
}
}
// If we completed the inner loop, we found a
// match
if (j == m) {
// Return starting index
return i;
}
}
// No match found
return -1;
}
static void Main()
{
string txt = "geeksforgeeks";
string pat = "eks";
Console.WriteLine(firstOccurence(txt, pat));
}
}
function firstOccurence(txt, pat)
{
const n = txt.length;
const m = pat.length;
// Iterate through txt
for (let i = 0; i <= n - m; i++) {
// Check for substring match
let j;
for (j = 0; j < m; j++) {
// Mismatch found
if (txt[i + j] !== pat[j]) {
break;
}
}
// If we completed the inner loop, we found a match
if (j === m) {
// Return starting index
return i;
}
}
// No match found
return -1;
}
// Driver code
const txt = "geeksforgeeks";
const pat = "eks";
console.log(firstOccurence(txt, pat));
Output
5
Pattern Searching Algorithms - O(n + m) Time
There are several pattern searching algorithms, such as:
Please refer to Introduction to Pattern Searching to learn more about them.
In-built library functions
This approach uses a built-in function to find the first occurrence of pat in txt.
Most programming languages provide built-in functions to find the first occurrence of a substring. The commonly used functions are:
- C: strstr()
- C++: string::find()
- Java: String.indexOf()
- Python: str.find()
- C#: String.IndexOf()
- JavaScript: String.indexOf()
#include
using namespace std;
int firstOccurence(string &txt, string &pat)
{
// Find the first occurrence of pat in txt.
size_t idx = txt.find(pat);
// Return the index if pat is found, otherwise return -1.
if (idx != string::npos)
return idx;
return -1;
}
int main()
{
string txt = "GeeksForGeeks";
string pat = "For";
cout << firstOccurence(txt, pat);
return 0;
}
#include
#include
int firstOccurence(char *txt, char *pat)
{
// Find the first occurrence of pat in txt.
char *idx = strstr(txt, pat);
// Return the index if pat is found, otherwise return -1.
if (idx != NULL)
return (int)(idx - txt);
return -1;
}
int main()
{
char txt[] = "GeeksForGeeks";
char pat[] = "For";
printf("%d", firstOccurence(txt, pat));
return 0;
}
public class GFG {
public static int firstOccurence(String txt, String pat)
{
// Find the first occurrence of pat in txt.
int idx = txt.indexOf(pat);
// Return the index if pat is found, otherwise
// return -1.
if (idx != -1)
return idx;
return -1;
}
public static void main(String[] args)
{
String txt = "GeeksForGeeks";
String pat = "For";
System.out.println(firstOccurence(txt, pat));
}
}
def firstOccurence(txt, pat):
# Find the first occurrence of pat in txt.
idx = txt.find(pat)
# Return the index if pat is found, otherwise return -1.
if idx != -1:
return idx
return -1
if __name__ == "__main__":
txt = "GeeksForGeeks"
pat = "For"
print(firstOccurence(txt, pat))
using System;
class GFG {
static int firstOccurence(string txt, string pat)
{
// Find the first occurrence of pat in txt.
int idx = txt.IndexOf(pat);
// Return the index if pat is found, otherwise
// return -1.
if (idx != -1)
return idx;
return -1;
}
static void Main()
{
string txt = "GeeksForGeeks";
string pat = "For";
Console.WriteLine(firstOccurence(txt, pat));
}
}
function firstOccurence(txt, pat)
{
// Find the first occurrence of pat in txt.
let idx = txt.indexOf(pat);
// Return the index if pat is found, otherwise return
// -1.
if (idx !== -1)
return idx;
return -1;
}
// Driver Code
let txt = "GeeksForGeeks";
let pat = "For";
console.log(firstOccurence(txt, pat));
Output
5
Note: The time and space complexity of in-built functions may vary across different languages and implementations.