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 haystack and needle, return the index where the first copy of needle begins inside haystack, or -1 if needle does not appear in it. Indexes count characters from 0. This is the same job that Java's String.indexOf method does.

Example 1
Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" appears at index 0 and again at index 6. The first is 0.
Example 2
Input: haystack = "cscodeio", needle = "cscd"
Output: -1
Explanation: "cscd" does not appear anywhere in "cscodeio".
Solution

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. haystack is the text being searched, needle is the word we look for, and the answer is the index where the first copy of the needle begins.

Where could the needle begin? Take Example 2, where the haystack "cscodeio" has 8 characters and the needle "cscd" has 4. Lay the needle under the haystack so that its first character sits under some index, which we call the start, and compare the characters that line up. Look at the picture below.

The needle cscd laid under the haystack cscodeio at starts 0 to 4. At start 0 three characters match, then o differs from d. At starts 1, 3 and 4 the first character differs, and at start 2 one character matches. Start 5 would leave too few characters, so the answer is -1.

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. In Example 2, n is 8 and m is 4, so the starts run from 0 to 4, the five rows of the picture.

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 j counts the characters matched so far. It begins at 0 and goes up by one while the needle's character at index j equals the haystack's character at index start + j. It stops at the first character that differs, or when it reaches m. If j reached m, every character of the needle matched.

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 j equals m straight away at start 0, and the method returns 0, the same answer String.indexOf gives.

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. KMP String Matching builds it step by step.

Java Solution

The method strStr works in these steps:

  1. First, store the two lengths: n for the haystack and m for the needle.
  2. Try each start with a loop that moves start up from 0 for as long as start + m <= n, so the needle always fits.
  3. Inside, a second loop counts the matched characters in j. It begins at 0 and moves up while j is below m and the haystack's character at start + j equals the needle's character at j.
  4. If j reached m, every character of the needle matched, so return start.
  5. If the first loop ends without a full match, return -1.

The main method runs both examples, a needle in the middle and one at the very end, a needle longer than the haystack, a haystack where several starts match partly, and an empty needle. Each line also shows what String.indexOf returns for the same two strings.

Java
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:

Output
"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 gives in brackets. Example 2 returns -1 after the five tries from the picture, and "but" is found at 3, after starts 0, 1 and 2 fail on their first letter.

Look at the line for "cscodeio" and "io": the needle sits in the last two characters, at 6. That is the last start the loop allows, because 6 + 2 is exactly 8. In "aaaaab", starts 0, 1 and 2 each match two letters a and then fail on the b, so the answer is 3. The needle "abcd" never fits in "abc", so the loop does not run, and the empty needle returns 0.

The loop condition start + m <= n matters. Written as start < n, the loop also tries starts where the needle runs past the end of the haystack. For haystack "abc" and needle "cd", start 2 matches the c and then reads index 3, so the method throws a StringIndexOutOfBoundsException instead of returning -1.

The original implementation, IndexOfFirstOccurrenceInAString.java, is on GitHub.

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, start and j, and never copies either string.

The Z-function is another way to search for a needle with work that grows only with n + m.