Write an efficient algorithm to implement the strstr function in Java, which returns the index of the first occurrence of a string in another string.

The prototype of the strstr() function is int strstr(String X, String Y);

Practice this problem

1. Iterative Implementation (Naive)

Here’s an iterative implementation of the strstr(X, Y) function. It returns the index of the first occurrence of Y in X or -1 if Y is not part of X.

Download  Run Code

Output:

The index of the first occurrence of Y in X is 9

 
The time complexity of this solution is O(m.n) where m and n are the length of string X and Y, respectively.

2. Using KMP Algorithm (Efficient)

We can even use KMP Algorithm to solve this problem, which offers O(m + n) complexity where m and n are lengths of string X and Y, respectively.

Download  Run Code

Output:

The index of the first occurrence of Y in X is 9

 
Also See:

Implement strstr() function in C (Iterative & Recursive)