Find the Index of the First Occurrence in a String

Pattern: Pattern matching

easy

KMP. First build lps for the needle, the longest border of each prefix. Then scan the haystack once; after a mismatch the needle slides so that lps characters still match, and the haystack index never moves back.

The problem

Given two strings haystack and needle, return the index of the first place where needle appears in haystack, or -1 if it never does. For example, "sadbutsad" with "sad" gives 0, and "leetcode" with "leeto" gives -1.

The function name strStr matches LeetCode. Use the link above for the exact statement and limits. Built-in searches would solve it, but this guide writes KMP, which is O(n + m) in every case.

Think first

  • The naive search slides the needle by one after a mismatch. What work does it repeat?
  • After matching abab and failing, which part of what you matched could still be the start of a match?
  • How can you compute that for every prefix of the needle in advance?

Hints

    Brute force, and why it fails

    Try every start position and compare up to m characters: O(n × m), for example on "aaaa…ab" with "aaab". KMP is O(n + m).

    The key insight

    A mismatch does not waste what was matched. The lps table says exactly how much of it can be reused, so the text is read only once.

    Dry run

    a0 
    b1 
    a2 
    b3 
    c4 
    lps0 0 1 2 0

    haystack = abababcabab and needle = ababc. lps for ababc is 0 0 1 2 0. For example, abab ends with ab, which is also its start.

    Step 1 of 4

    The plan

    build lps for needle
    i = 0, j = 0
    while i < n:
        if haystack[i] == needle[j]:
            i = i + 1; j = j + 1
            if j == m: return i - m
        else if j > 0: j = lps[j - 1]
        else: i = i + 1
    return -1
    

    Complexity

    Time
    O(n + m)
    Space
    O(m)

    Building lps is O(m). In the scan, every step either moves i forward or makes j smaller, and j can only grow as fast as i. The lps table takes O(m).

    Edge cases

    • Needle longer than haystack: -1.
    • Needle equals haystack: 0.
    • Overlapping starts, as in "aaaaab" with "aab": 3.
    I've built my logic, show the code

    Java

    class Solution {
        public int strStr(String haystack, String needle) {
            int m = needle.length();
            int[] lps = new int[m];                  // lps[i]: longest proper prefix of needle[0..i] that is also a suffix
            for (int i = 1, len = 0; i < m; ) {
                if (needle.charAt(i) == needle.charAt(len)) lps[i++] = ++len;
                else if (len > 0) len = lps[len - 1];   // fall back to a shorter border
                else lps[i++] = 0;
            }
            for (int i = 0, j = 0; i < haystack.length(); ) {   // j = how much of needle matches so far
                if (haystack.charAt(i) == needle.charAt(j)) {
                    i++;
                    j++;
                    if (j == m) return i - m;            // a full match ends at i - 1
                } else if (j > 0) {
                    j = lps[j - 1];                      // keep the part that still matches; i does not move back
                } else {
                    i++;
                }
            }
            return -1;
        }
    }

    C++

    class Solution {
    public:
        int strStr(string haystack, string needle) {
            int m = static_cast<int>(needle.size()), n = static_cast<int>(haystack.size());
            vector<int> lps(m, 0);                   // lps[i]: longest proper prefix of needle[0..i] that is also a suffix
            for (int i = 1, len = 0; i < m; ) {
                if (needle[i] == needle[len]) lps[i++] = ++len;
                else if (len > 0) len = lps[len - 1];   // fall back to a shorter border
                else lps[i++] = 0;
            }
            for (int i = 0, j = 0; i < n; ) {        // j = how much of needle matches so far
                if (haystack[i] == needle[j]) {
                    i++;
                    j++;
                    if (j == m) return i - m;            // a full match ends at i - 1
                } else if (j > 0) {
                    j = lps[j - 1];                      // keep the part that still matches; i does not move back
                } else {
                    i++;
                }
            }
            return -1;
        }
    };

    Python

    class Solution:
        def strStr(self, haystack: str, needle: str) -> int:
            m = len(needle)
            lps = [0] * m                            # lps[i]: longest proper prefix of needle[:i+1] that is also a suffix
            i, length = 1, 0
            while i < m:
                if needle[i] == needle[length]:
                    length += 1
                    lps[i] = length
                    i += 1
                elif length > 0:
                    length = lps[length - 1]         # fall back to a shorter border
                else:
                    i += 1
            i = j = 0                                # j = how much of needle matches so far
            while i < len(haystack):
                if haystack[i] == needle[j]:
                    i += 1
                    j += 1
                    if j == m:
                        return i - m                 # a full match ends at i - 1
                elif j > 0:
                    j = lps[j - 1]                   # keep the part that still matches; i does not move back
                else:
                    i += 1
            return -1

    Common mistakes

    • Moving i back after a mismatch, which turns KMP back into the naive search.
    • Setting j = lps[j] instead of lps[j - 1].
    • Building lps with len = lps[len] instead of lps[len - 1].

    Similar problems