Find The Index of The First Occurrence in a String
Find where one string first appears inside another by trying each starting position in turn.
Given two strings haystackneedleneedlehaystackneedleString.indexOf
Example 1
Output: 0
Explanation: "sad" appears at index 0 and again at index 6. The first is 0.
Example 2
Output: -1
Explanation: "cscd" does not appear anywhere in "cscodeio".
The Idea
You have probably used Find in a browser or a text editor: you type a word, and it jumps to the first place where that word appears. This problem asks for the same search. haystackneedle
Where could the needle begin? Take Example 2, where the haystack "cscodeio""cscd"
In the row labelled start 0, the first three characters match: c, s and c. The fourth does not, because the haystack has o where the needle has d. So the needle does not begin at 0, and there is no point in comparing anything else in that row. In the rows labelled start 1, start 3 and start 4, the very first character already differs, and start 2 matches one c before it fails.
Why does the picture stop at start 4? From start 5, only e, i and o are left in the haystack, three characters for the four of cscd. No later start has more room, so the needle appears nowhere, and the answer is -1.
So the search is a short list of tries: put the needle at each start where it still fits, compare from left to right, and give up on that start at the first character that differs. The first start where every character matches is the answer. In Example 1 that happens on the very first try, at start 0, so the second copy of "sad" at index 6 is never reached.
Solution Approach
Turning that idea into code means settling three things: which starts to try, how to compare at one start, and what to return. It also helps to know when this search gets slow, and how a smarter method avoids that.
Which starts to try
Which starts can hold the needle? Call the length of the haystack n and the length of the needle m. A start is worth trying only while the needle still fits, which means start + m <= n
The same check covers a needle longer than the haystack. Then not even start 0 fits, so nothing is compared and the answer is -1.
Comparing at one start
How do we compare the needle at one start? A counter jj
What to return
What does the method return? The starts are tried from left to right, so the first full match is also the first copy of the needle, and the method can return that start at once. If no start gives a full match, it returns -1.
An empty needle has nothing to compare. Its m is 0, so jString.indexOf
When the simple search gets slow
How much work does all this take? On ordinary text, most starts fail on their first or second character, so each try is short. The slow case is a haystack where the needle almost matches at every start.
Take a haystack of 10,000 letters a followed by one b, and a needle of 99 letters a followed by one b. At every start, 99 characters match before the b fails. The method makes 990,200 character comparisons before it finds the needle at index 9,901.
Reusing characters that already matched
Can those repeated comparisons be avoided? Look at start 0 of Example 2 again. After it fails, the simple method moves on to start 1 and then start 2, and reads the s and the second c again, although it has just matched them. Their values are known without looking: they are the first characters of the needle.
The matched part, csc, ends in c, and the needle begins with c. So the search can go on with one character already counted as matched, without moving back in the haystack. A method built on this idea is the Knuth-Morris-Pratt algorithm, named after its three authors and usually called KMP. It first works out, for each beginning of the needle, how much of a match can be kept after a mismatch.
KMP is an optional improvement. On the haystack of a's and one b above, it makes 19,902 comparisons instead of 990,200, and its work grows only with n + m on any input.
Java Solution
The method strStr
- First, store the two lengths:
for the haystack andn for the needle.m - Try each start with a loop that moves
up from 0 for as long asstart , so the needle always fits.start + m <= n - Inside, a second loop counts the matched characters in
. It begins at 0 and moves up whilej is belowj and the haystack's character atm equals the needle's character atstart + j .j - If
reachedj , every character of the needle matched, so returnm .start - If the first loop ends without a full match, return -1.
The mainString.indexOf
public class FindTheIndexOfTheFirstOccurrenceInAString {
public static int strStr(String haystack, String needle) {
int n = haystack.length();
int m = needle.length();
for (int start = 0; start + m <= n; start++) { // the needle must still fit
int j = 0;
while (j < m && haystack.charAt(start + j) == needle.charAt(j)) {
j++; // one more character matched
}
if (j == m) {
return start; // every character matched
}
}
return -1;
}
static void show(String haystack, String needle) {
System.out.println("\"" + haystack + "\", \"" + needle + "\" -> "
+ strStr(haystack, needle) + " (indexOf: " + haystack.indexOf(needle) + ")");
}
public static void main(String[] args) {
show("sadbutsad", "sad");
show("cscodeio", "cscd");
show("sadbutsad", "but");
show("cscodeio", "io");
show("abc", "abcd");
show("aaaaab", "aab");
show("abc", "");
}
}
Running it prints:
"sadbutsad", "sad" -> 0 (indexOf: 0)
"cscodeio", "cscd" -> -1 (indexOf: -1)
"sadbutsad", "but" -> 3 (indexOf: 3)
"cscodeio", "io" -> 6 (indexOf: 6)
"abc", "abcd" -> -1 (indexOf: -1)
"aaaaab", "aab" -> 3 (indexOf: 3)
"abc", "" -> 0 (indexOf: 0)
On every line, the number after the arrow matches the one indexOf"but"
Look at the line for "cscodeio""io""aaaaab""abcd""abc"
The loop condition start + m <= nstart < n"abc""cd"StringIndexOutOfBoundsException
The original implementation,
Complexity
The work is the character comparisons of the inner loop, added up over all the starts the outer loop tries.
- Time: O(n × m) in the worst case, because the loop tries up to n - m + 1 starts and each one can compare up to m characters before it fails. The haystack of a's with one b is such a case. On ordinary text most starts fail within a character or two, so the total stays close to n.
- Space: O(1), because the method keeps only
,n ,m andstart , and never copies either string.j
The